Leetcode - Remove Duplicates from Sorted List

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 deleteDuplicates(ListNode head) {
        if (head == null || head.next == null)
            return head;
        ListNode temp = head;
        ListNode post = temp.next;
        while (temp != null) {
            while (post != null && post.val == temp.val)
                post = post.next;
            temp.next = post;
            temp = post;
        }
        return head;
    }
}

My test result:

Paste_Image.png

这道题目比较简单,没什么好分析的。

代码写的太丑了。更新如下:

public ListNode deleteDuplicates(ListNode head) {
        if (head == null || head.next == null)
            return head;
        ListNode p = head;
        while (p.next != null) {
            if (p.next.val == p.val)
                p.next = p.next.next;
            else
                p = p.next;
        }
        return head;
    }

**
总结: linked list remove duplicates
**

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 deleteDuplicates(ListNode head) {
        if (head == null || head.next == null)
            return head;
        ListNode pre = head;
        ListNode curr = head.next;
        while (curr != null) {
            if (curr.val == pre.val) {
                pre.next = curr.next;
                curr = curr.next;
            }
            else {
                pre = curr;
                curr = curr.next;
            }
        }
        return head;
    }
}

感觉我这次写的思路就很清晰啊。
简单题,没什么好说的。

Anyway, Good luck, Richardo!

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

推荐阅读更多精彩内容