题目
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
.
可以双指针遍历一下删一段,也可以单指针遍历,一次删一个。这里是双指针的写法。
代码
public class RemoveDuplicatesFromSortedList { public ListNode deleteDuplicates(ListNode head) { if (head == null) { return head; } ListNode p = head; ListNode q = head.next; while (q != null) { if (q.val != p.val) { p.next = q; p = q; } q = q.next; } p.next = q; return head; } }
LeetCode | Remove Duplicates from Sorted List,布布扣,bubuko.com
LeetCode | Remove Duplicates from Sorted List
原文:http://blog.csdn.net/perfect8886/article/details/21318943