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

LeetCode Remove Duplicates from Sorted List

时间:2014-10-29 15:02:12      阅读:178      评论:0      收藏:0      [点我收藏+]

标签:io   ar   java   for   on   amp   ad   ef   as   

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.



输入排序过的链表,删除相同的元素。


挺简单的题目,头脑有点乱,搞的了做了半小时才做出来。。


/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public ListNode deleteDuplicates(ListNode head) {
        if(head==null||head.next==null) //空结点或者单节点直接返回
            return head;
        ListNode t = head;
        while(true){
            if(t==null||t.next==null) //到链表尾或者下一个是链表尾
                break;  
            while(t.next!=null&&t.next.val==t.val) //迭代排除相同的,注意考虑到了链表尾
                t.next=t.next.next;
            t= t.next;
        }
        return head;
    }
}


LeetCode Remove Duplicates from Sorted List

标签:io   ar   java   for   on   amp   ad   ef   as   

原文地址:http://blog.csdn.net/zhuangjingyang/article/details/40584401

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