[LeetCode] Remove Duplicates from Sorted List 移除有序連結串列中的重複項
阿新 • • 發佈:2018-12-27
Given a sorted linked list, delete all duplicates such that each element appear only once.
For example,
Given 1->1->2
, return 1->2
.
Given 1->1->2->3->3
, return 1->2->3
.
移除有序連結串列中的重複項需要定義個指標指向該連結串列的第一個元素,然後第一個元素和第二個元素比較,如果重複了,則刪掉第二個元素,如果不重複,指標指向第二個元素。這樣遍歷完整個連結串列,則剩下的元素沒有重複項。程式碼如下:
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode *deleteDuplicates(ListNode *head) { if (!head || !head->next) return head; ListNode*start = head; while (start && start->next) { if (start->val == start->next->val) { ListNode *tmp = start->next; start->next = start->next->next; delete tmp; } else start = start->next; }return head; } };