题目:
第一次刷的时候漏掉了这道题。
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 ) return head; ListNode dummpy(-1); dummpy.next = head; ListNode* pre = head; ListNode* curr = head->next; while (curr) { if ( curr->val!=pre->val ) { pre = curr; curr = curr->next; } else { pre->next = curr->next; curr = curr->next; } } return dummpy.next; } };
tips:
纠结了一下才AC。原因是第一次写的时候:
pre = curr;
curr = curr->next;