Question:
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
.
分析:
一旦重复全部删掉,利用好previous这个变量并在找到重复的时候嵌入一个while循环即可。
Code:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode deleteDuplicates(ListNode head) {
// Start typing your Java solution below
// DO NOT write main() function
ListNode start = new ListNode(0);
start.next = head;
ListNode p = start, c = head;
while(c!=null){
if(c.next!=null && c.val==c.next.val){
int tmp = c.val;
while(c!=null && c.val==tmp) c = c.next;
p.next = c;
continue;
}
p = p.next;
c = c.next;
}
return start.next;
}
}
总结:
第一次做的时候以为是难题,花费了很多时间。后来发现完全是自己见识太少,思路局限太多导致。