LeetCode--Remove Duplicates from Sorted List

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

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

Solution:从排好序的链表中移除重复节点。

思路:

1)输入的是空链表;

2)由于是排好序的,因此重复元素只会接连出现,因此用两个指针遍历链表即可。

解决:

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

 

posted @ 2015-08-29 20:39  江湖小妞  阅读(154)  评论(0编辑  收藏  举报