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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容