题目:
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.
Subscribe to see which companies asked this question
思路:
(为了使头结点的操作方便,创建一个伪头结点指向头结点,使得头结点的操作没有特殊性)
创建两个指针第一个指针指向要判断序列结点,第二个指针来判断之后的结点是不是与这个结点之前的数值一样
1)如果不同,第一个指针就可以向后移一个步数,第二个指针重新指向第一个指针后面的,然后重复上述操作
2)如果相同,则第二个指针一直后移,直到与第一个之后后面的数值不同,然后重复上述操作
具体代码实现:
/**
* 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) {
if(head == null){
return null;
}
if(head.next == null){
return head;
}
ListNode phead = new ListNode(0);
phead.next = head;
ListNode p = phead;
ListNode end = p.next;
while(p.next != null){
int temp = p.next.val;
if(end.next == null){
break;
}
if(end.next.val != temp){
p = p.next;
end = p.next;
}else{
while(end.next!=null && end.next.val == temp){
end = end.next;
}
p.next = end.next;
end = p.next;
}
}
return phead.next;
}
}