Leetcode_Linked --83. Remove Duplicates from Sorted List [easy]
阿新 • • 發佈:2018-12-15
Given a sorted linked list, delete all duplicates such that each element appear only once. 給定一個已排序連結串列,刪除其中重複的元素,使其每個元素只出現一次
Example 1:
Input: 1->1->2
Output: 1->2
Example 2:
Input: 1->1->2->3->3
Output: 1->2->3
Solution:
Python # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def deleteDuplicates(self, head): """ :type head: ListNode :rtype: ListNode """ dummy = head #建立一個指向連結串列的指標 while head and head.next: while head.val == head.next.val: if head.next.next: #如果head.next.next存在,則跨過重複的節點,將head.next.next賦給head.next head.next = head.next.next else: #當head.next.next不存在的時候且head.val == head.next.val,表明最後兩個節點相同,那麼丟棄最後一個節點,跳出迴圈(重要!) head.next = None break head = head.next #如果head與head.next值不同,那麼head向後移動 return dummy
C++思路與Python相同
C++ /** * 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) { ListNode *dummy = head; while(head){ while (head->next && head->val ==head->next->val){ if (head->next->next){ head->next = head->next->next; } else{ head->next = NULL; } } head = head->next; } return dummy; } };