83. Remove Duplicates from Sorted List
Problem:
Given a sorted linked list, delete all duplicates such that each element appear only once.
For example,
Given
Given
05/01/2018 update:
A better solution can be applied to II.
Given
1->1->2
, return 1->2
.Given
1->1->2->3->3
, return 1->2->3
.05/01/2018 update:
A better solution can be applied to II.
public ListNode deleteDuplicates(ListNode head) { ListNode current = head; while (current != null && current.next != null) { if (current.next.val == current.val) { current.next = current.next.next; } else { current = current.next; } } return head; }
Analysis:
看了II,这道题就非常简答了。
We can always move head to head.next. When encounters duplicate, use head.next = head.next.next.
Solution:
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ class Solution { public ListNode deleteDuplicates(ListNode head) { ListNode dummy = new ListNode(0); dummy.next = head; while (head != null) { while (head != null && head.next != null && head.val == head.next.val) { head.next = head.next.next; } head = head.next; } return dummy.next; } }
评论
发表评论