83. 刪除排序連結串列中的重複元素
阿新 • • 發佈:2021-06-15
1 /** 2 * Definition for singly-linked list. 3 * struct ListNode { 4 * int val; 5 * struct ListNode *next; 6 * }; 7 */ 8 9 /*思路:先建立一個帶頭結點的空連結串列,然後先插入第一個元素,然後再比較舊連結串列和新連結串列的元素值,不同再插入, 10 也可以把不同的值都放入一個數組,然後再根據陣列建表 11 */ 12 struct ListNode* deleteDuplicates(struct ListNode* head){ 13struct ListNode * h1 = (struct ListNode * )malloc(sizeof(struct ListNode)),*tail; 14 h1->next = NULL; 15 tail = h1; 16 int count = 0; 17 while(head) 18 { 19 //if(head->val != head->next->val)這句到了最後一個節點就會出錯 20 if(count==0) 21 { 22 structListNode * h2 = (struct ListNode * )malloc(sizeof(struct ListNode)); 23 h2->val = head->val; 24 h2->next = NULL; 25 tail->next = h2; 26 tail = h2; 27 count++; 28 }else{ 29 if(tail->val!=head->val){30 struct ListNode * h2 = (struct ListNode * )malloc(sizeof(struct ListNode)); 31 h2->val = head->val; 32 h2->next = NULL; 33 tail->next = h2; 34 tail = h2; 35 } 36 } 37 head = head->next; 38 } 39 40 return h1->next; 41 }