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

LeetCode--Remove Duplicates from Sorted List

时间:2014-10-21 11:42:57      阅读:165      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   io   ar   for   sp   div   on   

 

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.

 

LeetCode上很简单的一道题,处理链表将链表中重复的数值去除只保留一个。大致流程如下:

1.先判断链表是否为空或只有一个结点,是的话直接返回,否则进行一般处理。

2.一般处理,以head作为循环变量,当head不为最后的尾结点时进行循环,从头到尾依次将head和head.next的值两两比较。

3.注意head.val==nextNode.val时,考虑超过两个重复值的情况,将nextNode去除并赋值去除的结点的下一个结点,head结点不变。

 head.val!=nextNode.val时,head和nextNode同时向后移动。

 

 1 /**
 2  * Definition for singly-linked list.
 3  * public class ListNode {
 4  *     int val;
 5  *     ListNode next;
 6  *     ListNode(int x) {
 7  *         val = x;
 8  *         next = null;
 9  *     }
10  * }
11  */
12 public class Solution {
13     public ListNode deleteDuplicates(ListNode head) {
14         ListNode result = head;
15         if(head==null||head.next==null){
16             return head;
17         }else{
18             ListNode nextNode = head.next;
19             while(nextNode!=null){
20                if(head.val == nextNode.val)
21                     {
22                         head.next = nextNode.next;
23                         nextNode = head.next;
24                     }
25                 else if(head.val != nextNode.val){
26                     head = nextNode;
27                     nextNode = nextNode.next;
28                 }
29             }
30             
31         }
32         return result;
33     }
34 }

 

LeetCode--Remove Duplicates from Sorted List

标签:style   blog   color   io   ar   for   sp   div   on   

原文地址:http://www.cnblogs.com/zhoujunfu/p/4039582.html

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