1. 程式人生 > 實用技巧 >【LeetCode】83. 刪除排序連結串列中的重複元素

【LeetCode】83. 刪除排序連結串列中的重複元素

【題目描述】

給定一個排序連結串列,刪除所有重複的元素,使得每個元素只出現一次。

示例1:

輸入: 1->1->2
輸出: 1->2
示例2:

輸入: 1->1->2->3->3
輸出: 1->2->3

來源:力扣(LeetCode)
連結:https://leetcode-cn.com/problems/remove-duplicates-from-sorted-list

【解題思路】

注意此題與【LeetCode】02.01. 移除重複節點的區別,此題中連結串列為有序連結串列;

因而可以進行優化,遍歷連結串列一遍,逐個將當前節點與其下一個節點比較,如果相等,則刪除其下一個節點,只需遍歷一遍即可。

【提交程式碼】

 1 /**
 2  * Definition for singly-linked list.
 3  * struct ListNode {
 4  *     int val;
 5  *     struct ListNode *next;
 6  * };
 7  */
 8 
 9 #if 0
10 struct ListNode* deleteDuplicates(struct ListNode* head){
11     struct ListNode *p;
12     struct ListNode *pre;
13     struct ListNode *cur;
14 int val; 15 16 p = head; 17 18 while( p != NULL ) 19 { 20 val = p->val; 21 22 pre = p; 23 cur = p->next; 24 while( cur != NULL ) 25 { 26 if( cur->val == val ) // 刪除當前的節點 27 { 28 pre->next = cur->next; //
pre的next指向cur的next,相當於斷開了cur,即意為刪除 29 } 30 else 31 { 32 pre = pre->next; 33 } 34 cur = cur->next; 35 } 36 37 p = p->next; 38 } 39 40 return head; 41 } 42 #endif 43 // 由於陣列本身有序,可以利用這個特性,遍歷一遍即可; 44 struct ListNode* deleteDuplicates(struct ListNode* head){ 45 struct ListNode *cur; 46 47 cur = head; 48 49 while( cur != NULL && cur->next != NULL ) 50 { 51 if( cur->val == cur->next->val ) 52 { 53 cur->next = cur->next->next; 54 } 55 else 56 { 57 cur = cur->next; 58 } 59 } 60 return head; 61 }