Given a sorted linked list, delete all duplicates such that each element appear only once.node
For example,
Given 1->1->2
, return 1->2
.
Given 1->1->2->3->3
, return 1->2->3
.app
如題目所訴,去除遞增鏈表中重複值的節點。指針
剛開始思路以下:code
可是會有個問題,若是是{1,1,1},那麼遍歷到第一個1的時候,判斷和第二個1相同,則將第一個1的next指向第三個1.blog
程序結束,最後輸出爲{1,1},因此此方法行不通。element
/** * 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 *node = head; while(NULL != node && NULL != node->next) { if(node->next->val == node->val) { node->next = node->next->next; } else { node = node->next; } } return head; } };