问题描述:
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.
我的解决思路:
用一个引用指向当前的节点,如果pre.val==pre.next.val,则把下一节点删除,否则就pre=pre.next;但是这里要注意,如果pre.val==pre.next.val时,当前节点不需要移动,应该考虑到1,1,1这种情况。
下面附上代码:
/**
* 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) {
ListNode pre = new ListNode(0);
pre = head;
while(pre!=null){
if(pre.next==null)
break;
if(pre.val==pre.next.val){
pre.next = pre.next.next;
}
else{
pre=pre.next;
}
}
return head;
}
}