Remove Duplicates from Sorted List
Total Accepted: 89961 Total Submissions: 253975 Difficulty: Easy
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
.
思路:
维持两具指针指向当前节点与相邻的下一个节点。将当前节点与下一个节点值进行比较,相等,则删除下一个节点,不等则将两个指针同时递增1步。
1 /** 2 * Definition for singly-linked list. 3 * struct ListNode { 4 * int val; 5 * ListNode *next; 6 * ListNode(int x) : val(x), next(NULL) {} 7 * }; 8 */ 9 class Solution { 10 public: 11 ListNode* deleteDuplicates(ListNode* head) { 12 if(head==NULL){ 13 return head; 14 } 15 ListNode* p=head; 16 ListNode* q=p->next; 17 ListNode* tem; 18 while(q!=NULL){ 19 if(q->val!=p->val){ 20 p=q; 21 q=q->next; 22 }else{ 23 tem=q; 24 q=q->next; 25 p->next=q; 26 delete tem; 27 } 28 } 29 return head; 30 }
时间: 2024-12-24 19:53:00