LeetCode 203. Remove Linked List Elements

Remove all elements from a linked list of integers that have value val.

Example
Given: 1 --> 2 --> 6 --> 3 --> 4 --> 5 --> 6, val = 6
Return:* 1 --> 2 --> 3 --> 4 --> 5

Credits:Special thanks to @mithmatt for adding this problem and creating all test cases.

題意:給一個鏈表,給一個數(shù)字,把鏈表中和這個數(shù)字的結(jié)點(diǎn)值相同的結(jié)點(diǎn),全部都干掉

思路:自己創(chuàng)建一個頭結(jié)點(diǎn),用來完成后,還能找到這個鏈表,然后就可以往后遍歷了,當(dāng)發(fā)現(xiàn)遇到同樣的值直接跳過就可以了,最后返回這個頭結(jié)點(diǎn)了。

java代碼:

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
  public ListNode removeElements(ListNode head, int val) {
       
      ListNode first = new ListNode(1);
        first.next = head;

        ListNode temp = first;

        while (temp.next != null) {
            if (temp.next.val == val) {
                temp.next = temp.next.next;
            } else {
                temp = temp.next;
            }
        }
        return first.next;
        
    }
}



最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容