面試題57:刪除連結串列中的重複節點
阿新 • • 發佈:2019-02-05
題目:在一個排序的連結串列中,存在重複的結點,請刪除該連結串列中重複的結點,重複的結點不保留,返回連結串列頭指標。 例如,連結串列1->2->3->3->4->4->5 處理後為 1->2->5。
程式碼如下:
<pre name="code" class="cpp" style="color: rgb(51, 51, 51); font-size: 14px; line-height: 22.4px;">struct ListNode { int val; struct ListNode *next; ListNode(int x) : val(x), next(NULL) { } }; class Solution { public: ListNode* deleteDuplication(ListNode* pHead) { if(pHead == NULL) return NULL; ListNode *pre = new ListNode(0); ListNode *slow = pre; slow->next = pHead; ListNode *fast = slow->next; bool sign = false; ListNode *temp = NULL; while(fast != NULL && fast->next != NULL) { if(fast->val == fast->next->val) { temp = fast->next; delete fast; fast = NULL; fast = temp; sign = true; } else { if(sign) { slow->next = fast->next; fast = fast->next; sign = false; } else { slow = fast; fast = slow->next; } } } if(fast->next == NULL) { if(sign) slow->next = fast->next; else slow->next = fast; } return pre->next; } };