/**
* 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) {
ListNode x = new ListNode(-1);
ListNode cur = head;
if(cur == null)
return cur;
ListNode pre = head.next;
if(pre == null)
return cur;
x.next = cur;
int lastV=cur.val;
while(pre != null){
if(pre.val == lastV){
pre = pre.next;
cur.next = null;
}
else{
cur.next = pre;
cur = cur.next;
lastV = cur.val;
pre = pre.next;
}
}
return x.next;
}
}
分析:
题目中是链表是有序的,这样用两个指针,前面一个用于探测是否相同不,后面一个用于连接。
前面的探测有两种结果:如果相同,前指针继续走下去;如果不相同,后指针的连接前指针,前指针继续走下去。
注意点:做了2个链表的题目,感觉是在原来的基础上构造链表的时候,要及时将新链表的next设置能null,防止以前的数据影响链表结构。
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
.