标签:
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
.
要考虑多种情况比如:
1->1->1->3->3->3->3,
1->1->1
1->2->2->3,
1->2->2
设置3个指针,前指针pre和前前指针prepre指向头结点,当前指pcur针指向头结点下一个指针。
设置一个标志位FLAG,判断pcur和pre是否相等过。
1 /** 2 * Definition for singly-linked list. 3 * struct ListNode { 4 * int val; 5 * struct ListNode *next; 6 * }; 7 */ 8 struct ListNode* deleteDuplicates(struct ListNode* head) { 9 struct ListNode* prepre; 10 struct ListNode* pre; 11 struct ListNode* pcur; 12 int flag = 0; //标志位初始化为0 13 if(head == NULL) 14 return NULL; 15 prepre = head; 16 pre = head; 17 pcur = head->next; 18 while(pcur != NULL){ 19 if(pcur->val != pre->val && flag == 0){ //如果前指针和当前指针不相等,并且之间没有相同元素,3个指针都指向下一个 20 prepre = pre; 21 pre = pcur; 22 pcur = pcur->next; 23 } 24 else if(pcur->val == pre->val){ //如果前指针和当前指针相等 25 if(pcur->next == NULL){ //如果当前指针为最后一个元素 26 if(prepre == head && prepre->val == pcur->val) //判断前前指针是否是头结点,并且和当前元素是否相等判断,比如1->1->1 27 return NULL; 28 else{ 29 prepre->next = NULL; 30 break; 31 } 32 } 33 flag = 1; 34 pcur = pcur->next; 35 } 36 else if(pcur->val != pre->val && flag == 1){ //如果前指针和当前指针不相等,之间有相同元素 37 if(prepre == head && prepre->val == pre->val){ //判断前前指针是否是头结点并且和前指针是否相等2->2->2->3 38 head = pcur; 39 prepre = head; 40 pre = pcur; 41 pcur = pcur->next; 42 flag = 0; 43 } 44 else{ 45 prepre->next = pcur; 46 pre = pcur; 47 pcur = pcur->next; 48 flag = 0; 49 } 50 } 51 } 52 return head; 53 }
Remove Duplicates from Sorted List II
标签:
原文地址:http://www.cnblogs.com/boluo007/p/5470852.html