删除链表中相邻的重复节点, 当出现重复节点,只移动后继节点至后继的后继,相当于删除,而头结点不动;当不再重复,则同时移动头结点和后继节点
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* deleteDuplicates(ListNode* head) {
if(head==NULL || head->next==NULL) return head;
ListNode* p=head->next;
ListNode* q=head;
while(p){
if(p->val == q->val){
p=p->next;
q->next=q->next->next;
}else{
p=p->next;
q=q->next;
}
}
return head;
}
};
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode deleteDuplicates(ListNode head) {
if(head==null || head.next==null)
return head;
ListNode p=head;
ListNode q=head.next;
while(q!=null){
if(p.val==q.val){
q=q.next;
p.next=p.next.next;
}else{
q=q.next;
p=p.next;
}
}
return head;
}
}