83. Remove Duplicates from Sorted List

Given a sorted linked list, delete all duplicates such that each element appear only once.

Example 1:

Input: 1->1->2
Output: 1->2

Example 2:

Input: 1->1->2->3->3
Output: 1->2->3

去重,因为已经排序好,直接比较不同的结点的数据域放进去就行。

 1 /**
 2  * Definition for singly-linked list.
 3  * struct ListNode {
 4  *     int val;
 5  *     struct ListNode *next;
 6  * };
 7  */
 8 struct ListNode* deleteDuplicates(struct ListNode* head) {
 9     if(head==NULL)   return NULL;
10     struct ListNode *current=head,*tail=head;
11     while(current){
12         if(current->val!=tail->val){
13             tail->next=current; //符合条件的放到原本尾部的后面
14             tail=current;       //让正确的成为新的尾部
15         }
16         current=current->next;
17         tail->next=NULL;
18     }
19     return head;
20 }
21     

 

posted @ 2018-10-24 16:03  杜王町上班族  阅读(134)  评论(0编辑  收藏  举报