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.
解题思路:
设置两个指针一个node指向相同元素的最后一个值,一个lasthead指向相同元素的第一个元素,让lasthead元素直接指向node节点,这样就直接消除了中间重复的元素。
而为了让node移动到重复元素的最后一个,要用while循环将指针移动到相同元素的最后一个。注意当消除重复元素后,要将node指向下一个元素,让其开始下一次判断,而lasthead也是要移动到下一组的第一个,执行下一组的判断
Solution:
/**
* 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;
int v = head.val;
ListNode node = head.next;
ListNode lasthead = head;
while(node != null){
while(node != null && node.val == lasthead.val) node = node.next;
lasthead.next = node;
lasthead = node;
if(node != null) node = node.next;
}
return head;
}
}