TypechoJoeTheme

IT技术分享

统计

[LeetCode 83] Remove Duplicates from Sorted List [Java]

2018-02-26
/
0 评论
/
842 阅读
/
正在检测是否收录...
02/26

1. Description

Given a sorted linked list, delete all duplicates such that each element appear only once.

2. Example

Given 1->1->2, return 1->2.
Given 1->1->2->3->3, return 1->2->3.

3. Code

public class LeetCode0083 {

    class ListNode {
        int val;
        ListNode next;

        ListNode(int x) {
            val = x;
        }
    }

    public ListNode deleteDuplicates(ListNode head) {
        ListNode dummy = new ListNode(Integer.MIN_VALUE);
        dummy.next = head;
        ListNode p = head;
        ListNode pre = dummy;
        while (p != null) {
            if (p.val == pre.val) {
                p = p.next;
            } else {
                pre.next = p;
                pre = p;
                p = p.next;
            }
        }
        pre.next = null;
        return dummy.next;
    }
}
Linked
朗读
赞 · 0
版权属于:

IT技术分享

本文链接:

https://idunso.com/archives/1451/(转载时请注明本文出处及文章链接)