题目:
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) { ListNode *node = head; while (node != NULL && node->next != NULL) { if (node->val != node->next->val) { node = node->next; } else { ListNode *tmp_node = node->next; node->next = node->next->next; delete tmp_node; } } return head; } };