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; } * } */ public class Solution { public ListNode deleteDuplicates(ListNode head) { if( head == null || head.next == null) return head; ListNode result = head; ListNode flag = head; ListNode flag_next ; while( flag.next != null){ flag_next = flag.next; if( flag.val != flag_next.val ){ result.next = flag_next; result = result.next; } flag = flag_next; } result.next = null; return head; } }