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

Leetcode 83 Remove Duplicates from Sorted List (快慢指针)

时间:2015-02-15 12:05:02      阅读:140      评论:0      收藏:0      [点我收藏+]

标签:

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.

 

题目解析:

LinkedList果然是各种快慢指针的解题啊!

两个Node, 一个fast, 一个lower

如果lower.val == fast.val 就直接把中间的那个node跳掉, 也就是删除掉

如果不等, 就两个都move forward

 

注意特殊情况和while的循环条件就好~

 

很简单, 直接上代码:

 1 public ListNode deleteDuplicates(ListNode head) {
 2         if(head == null)
 3             return head;
 4         ListNode fast = head.next;
 5         ListNode lower = head;
 6         while(fast != null){
 7             if(fast.val != lower.val){
 8                 lower = lower.next;
 9             }else if(fast.val == lower.val){
10                 lower.next = fast.next;
11             }
12             fast = fast.next;
13         }   
14         return head;     
15     }

 

Leetcode 83 Remove Duplicates from Sorted List (快慢指针)

标签:

原文地址:http://www.cnblogs.com/sherry900105/p/4292621.html

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