Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.
For example,
Given 1->2->3->3->4->4->5, return 1->2->5.
Given 1->1->1->2->3, return 2->3.
具体代码如下:
/**
* 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) {
ListNode first = new ListNode(0);
ListNode last = first;
ListNode p = head;
while(head != null){
while(head.next != null){//p不动,head后移直到head.next与p不相等
if(p.val == head.next.val){
head = head.next;//相等循环
}else{
break;//不相等结束
}
}
if(p == head){//只有一个
last.next = p;//添加
last = last.next;
}
p = head = head.next;//有多个则不添加
last.next = null;//去掉关联
}
return first.next;
}
}
版权声明:本文为博主原创文章,未经博主允许不得转载。
leetCode 82.Remove Duplicates from Sorted List II (删除排序链表的重复II) 解题思路和方法
原文地址:http://blog.csdn.net/xygy8860/article/details/47002063