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
.
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
//思路:为了方便,最好加一个头结点(可能有对head连续几个结点值一样的),顺序查找相同的值,直到不相等(保存该位置值),然后开始删除重复的结点。
//此题个人未注意:NULL的判断其没有val可言!if(cur->next != NULL&&cur->val == cur->next->val) ,主要是对cur->next != NULL的没注意程序一直报Bug,以后的注意!!
ListNode *deleteDuplicates(ListNode *head) {
ListNode mynode(0);
ListNode *cur = head;
ListNode *pre = head;
ListNode *temp;
// if(head == NULL || head->next == NULL) return head;
mynode.next = head;
pre = &mynode;
cur = head;
while(cur != NULL )
{
if(cur->next != NULL&&cur->val == cur->next->val)
{
while(cur->next != NULL&&cur->val == cur->next->val)//直到找到不相等的
{
cur = cur->next;
}
cur = cur->next;//指向重复值的下一个结点
while(pre->next != cur)//开始删除中间重复的点!!
{
temp = pre->next;
pre->next = pre->next->next;
delete temp;
}
}
else
{
pre = pre->next;
cur = cur->next;
}
}
return mynode.next ;
}