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
原文:http://blog.csdn.net/zhuangjingyang/article/details/40584401