双指针法:
定义两个指针temp和cur,开始时,temp指向head,cur指向head.next。遍历链表,如果temp.val = cur.val,temp指向cur的下个节点,cur指针往后移一个节点,这时cur指向的节点为新节点,因此temp指针无需移动,如果temp.val != cur.val,temp和cur都各往后移动一个节点,知道遍历完链表。
class Solution {
public ListNode deleteDuplicates(ListNode head) {
ListNode temp = head,cur = head;
while(cur != null){
if(temp.val == cur.val){
temp.next = cur.next;
cur = temp.next;
}else{
temp = temp.next;
cur = cur.next;
}
}
return head;
}
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。