Remove Duplicates from Sorted List
题目:Given a sorted linked list, delete all duplicates such that each element appear only once.
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) { //https://leetcode.com/problems/remove-duplicates-from-sorted-list/ if(head==NULL||head->next==NULL) return head; ListNode *t=head; while(head->next!=NULL){ if(head->val==head->next->val){ ListNode *tmp = head->next->next; delete head->next; head->next = tmp; }else head=head->next; } return t; } };