码迷,mamicode.com
首页 > 其他好文 > 详细

Remove Duplicates from Sorted List

时间:2014-08-22 22:18:59      阅读:342      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   io   for   ar   div   log   amp   

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 class Solution {
 2 public:
 3     ListNode *deleteDuplicates( ListNode *head ) {
 4         if( !head ) { return head; }
 5         ListNode *node = head;
 6         while( node->next ) {
 7             if( node->val == node->next->val ) {
 8                 node->next = node->next->next;
 9             } else {
10                 node = node->next;
11             }
12         }
13         return head;
14     }
15 };

 

Remove Duplicates from Sorted List

标签:style   blog   color   io   for   ar   div   log   amp   

原文地址:http://www.cnblogs.com/moderate-fish/p/3930225.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!