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的题目,虽然非常简单,但是发现坑很多,建议手写几道。
另外思考下,如果不是sorted的,怎么办?
思考二,如果不是sorted,并且不让用额外的空间,怎么办?
/** * 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) { ListNode current = head; while(current != null){ if(current.next == null){ return head; } if(current.val == current.next.val){ current.next = current.next.next; } else{ current = current.next; } } return head; } }