标签:des style blog class code java
Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.
For
example,
Given 1->2->3->3->4->4->5
,
return 1->2->5
.
Given 1->1->1->2->3
,
return 2->3
.
思路:去掉重复的链表节点。使用两个指针pPre,pCur,并且定义一个flag。循环查找pCur和pCur->next相等的值的结点,如果有,则将flag赋值为true,并且删掉pCur->next这个结点更新链表,直到不同的点出现。然后判断flag的值,如果为true,则将pPre在不为空的情况下做如下设置pPre->next=pCur->next;为空则head=pCur->next.如果为false,则pPre=pCur;然后pPre=pPre->ext进行下次循环。
/** * 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) return NULL; ListNode *pPre=NULL; ListNode *pCur=head; while(pCur!=NULL) { bool flag=false; while(pCur->next!=NULL && pCur->val==pCur->next->val) { flag=true; pCur->next=pCur->next->next; } if(flag==true) { if(pPre!=NULL) pPre->next=pCur->next; else head=pCur->next; } else pPre=pCur; pCur=pCur->next; } return head; } };
Remove Duplicates from Sorted List II,布布扣,bubuko.com
Remove Duplicates from Sorted List II
标签:des style blog class code java
原文地址:http://www.cnblogs.com/awy-blog/p/3712846.html