82. Remove Duplicates from Sorted List II【Medium】
82. Remove Duplicates from Sorted List II【Medium】
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 /** 2 * Definition for singly-linked list. 3 * struct ListNode { 4 * int val; 5 * ListNode *next; 6 * ListNode(int x) : val(x), next(NULL) {} 7 * }; 8 */ 9 class Solution { 10 public: 11 ListNode* deleteDuplicates(ListNode* head) { 12 if (head == NULL || head->next == NULL) { 13 return head; 14 } 15 16 ListNode * dummy = new ListNode(INT_MIN); 17 dummy->next = head; 18 head = dummy; 19 int duplicate; 20 21 while (head->next != NULL && head->next->next != NULL) { 22 if (head->next->val == head->next->next->val) { 23 duplicate = head->next->val; 24 while (head->next != NULL && head->next->val == duplicate) { 25 ListNode * temp = head->next; 26 free(temp); 27 head->next = head->next->next; 28 } 29 } 30 else { 31 head = head->next; 32 } 33 } 34 return dummy->next; 35 36 } 37 };
nc
解法二:
1 class Solution { 2 public: 3 ListNode* deleteDuplicates(ListNode* head) { 4 if(!head) return head; 5 ListNode dummy(0); 6 dummy.next = head; 7 ListNode *pre = &dummy; 8 ListNode *cur = head; 9 10 while(cur && cur->next){ 11 while(cur->next && cur->val == cur->next->val) cur = cur->next; 12 if(pre->next == cur){ 13 pre = cur; 14 cur = cur->next; 15 } else { 16 cur = cur->next; 17 pre->next = cur; 18 } 19 } 20 21 return dummy.next; 22 } 23 };
参考了@liismn 的代码
解法三:
1 class Solution { 2 public: 3 ListNode* deleteDuplicates(ListNode* head) { 4 if(!head||!head->next) return head; 5 ListNode* dummy = new ListNode(0); 6 ListNode* tail = dummy; 7 int flag = true; // should the current head be added ? 8 while(head){ 9 while(head&&head->next&&head->val==head->next->val) 10 { 11 flag = false; // finds duplicate, set it to false 12 head = head->next; 13 } 14 if(flag) // if should be added 15 { 16 tail->next = head; 17 tail = tail->next; 18 } 19 head = head->next; 20 flag = true; // time for a new head value, set flag back to true 21 } 22 tail->next = nullptr; // Don't forget this... I did.. 23 return dummy->next; 24 } 25 };
参考了@GoGoDong 的代码
解法四:
1 public ListNode deleteDuplicates(ListNode head) { 2 if (head == null) return null; 3 4 if (head.next != null && head.val == head.next.val) { 5 while (head.next != null && head.val == head.next.val) { 6 head = head.next; 7 } 8 return deleteDuplicates(head.next); 9 } else { 10 head.next = deleteDuplicates(head.next); 11 } 12 return head; 13 }
递归,参考了@totalheap 的代码,还不太明白
posted on 2017-10-14 15:47 LastBattle 阅读(142) 评论(0) 编辑 收藏 举报