Leetcode 83 Remove Duplicates from Sorted List (快慢指针)
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果然是各种快慢指针的解题啊!
两个Node, 一个fast, 一个lower
如果lower.val == fast.val 就直接把中间的那个node跳掉, 也就是删除掉
如果不等, 就两个都move forward
注意特殊情况和while的循环条件就好~
很简单, 直接上代码:
1 public ListNode deleteDuplicates(ListNode head) { 2 if(head == null) 3 return head; 4 ListNode fast = head.next; 5 ListNode lower = head; 6 while(fast != null){ 7 if(fast.val != lower.val){ 8 lower = lower.next; 9 }else if(fast.val == lower.val){ 10 lower.next = fast.next; 11 } 12 fast = fast.next; 13 } 14 return head; 15 }