[Leetcode] Remove duplicates from sorted list 从已排序的链表中删除重复元素

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

For example,
Given1->1->2, return1->2.
Given1->1->2->3->3, return1->2->3.

思路:遍历链表。比较相邻的结点,若是有相等的情况,则cur不动,而将其后继从其next变为next->next;没有,则正常遍历就行。

 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     {
13         if(head==NULL)  return NULL;  //return head也可以
14         ListNode *cur=head;
15         while(cur->next)
16         {
17             if(cur->val==cur->next->val)
18                 cur->next=cur->next->next;
19             else
20                 cur=cur->next;
21         } 
22         return head;   
23     }
24 };

 

posted @ 2017-06-14 09:39  王大咩的图书馆  阅读(211)  评论(0编辑  收藏  举报