题目:
Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.
For example,
Given 1->2->3->3->4->4->5
, return 1->2->5
.
Given 1->1->1->2->3
, return 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 dummy(INT_MIN); dummy.next = head; ListNode *prev = &dummy; ListNode *p = head; while ( p && p->next ) { if ( p->val!=p->next->val ) { prev = p; p = p->next; } else { while ( p->next && p->val==p->next->val ) p = p->next; prev->next = p->next; p = p->next; } } return dummy.next; } };
Tips:
主要思路就是:如果遇上相同的,就用while循环一直往后过。
具体思路沿用了之前Python版的:http://www.cnblogs.com/xbf9xbf/p/4186852.html
时间: 2024-10-24 09:22:15