LeetCode Remove Duplicates from Sorted List II

来源:互联网 发布:软件销售笔试题库 编辑:程序博客网 时间:2024/05/29 15:41

题目

Given a sorted linked list, delete all nodes that have duplicate numbers, leaving onlydistinct 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) {        ListNode *pos=head,*next=head,*tail=NULL;//原链处理到的位置,下一个不同元素位置,新链的尾head=NULL;while(next!=NULL){while(next!=NULL&&next->val==pos->val)//寻找下一个不同的元素next=next->next;if(next==pos->next)//下一个元素在本元素之后一个位置,说明本元素是唯一的{if(head==NULL)//元素是新链的头{head=pos;tail=head;}else//不是新链的头{tail->next=pos;tail=pos;}}pos=next;}if(tail!=NULL)//处理尾部tail->next=NULL;return head;    }};


 

 

 

 

0 0
原创粉丝点击