题目要求:
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
.
思路:用两个指针,一个指向当前结点,一个指向后一个结点,如果当前结点的值等于后一个结点的值,就把后一个节点向后移一位,再去比较;如果不等于,就把两个指针都往后移。
/**
* 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||head.next==null)
{
return head;
}
ListNode cur=head;
ListNode next = head.next;
while(next!=null)
{
if(cur.val==next.val)
{
cur.next=next.next;
next = next.next;
}else
{
cur=next;
next=next.next;
}
}
return head;
}
}