Leetcode - Remove Linked List Elements

Paste_Image.png

My code:

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ListNode removeElements(ListNode head, int val) {
        if (head == null)
            return null;
        while (head != null && head.val == val)
            head = head.next;
        if (head == null)
            return null;
        ListNode temp = head;
        while (temp.next != null) {
            if (temp.next.val == val)
                temp.next = temp.next.next;
            else
                 temp = temp.next;
        }
        return head;
    }
}

My test result:

這道題目和剛剛差不多吧,只不過處理的是鏈表。 也簡單很多。
說個細節,之前也一直有過以為。

while (head != null && head.val == val)
            head = head.next;

這段如果改成:

while (head.val == val && head != null)
            head = head.next;

就會報錯。所以說,編譯器檢查while,if這類括號內的內容時(與邏輯),會先檢查左邊的再檢查右邊的,左邊的如果過不了,那就會立刻退出,不會再去看右邊的,即使右邊犯了嚴重的錯誤,比如空指針。
而在復制操作時,編譯器會先檢查右邊的值,計算出來后,在賦給左邊,所以即使某個值同時出現在左邊和右邊,但左邊的將會是新值,而右邊則是舊值。

**
總結:上面的與邏輯處理技巧得記住。
**

Anyway, Good luck, Richardo!

My code:

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ListNode removeElements(ListNode head, int val) {
        if (head == null) {
            return head;
        }
        
        ListNode dummy = new ListNode(-1);
        dummy.next = head;
        ListNode pre = dummy;
        ListNode curr = dummy.next;
        
        while (curr != null) {
            if (curr.val == val) {
                pre.next = curr.next;
                curr = pre.next;
            }
            else {
                curr = curr.next;
                pre = pre.next;
            }
        }
        
        return dummy.next;
    }
}

差不多的做法。
看以前的總結,還是很用心的。

Anyway, Good luck, Richardo! -- 08/15/2016

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容