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
.
题目标签:Linked List
题目给了我们一个 list,让我们去除中间的重复项。
设一个 cursor = head,遍历list,每一次比较 cursor 和 cursor.next,如果一样,发现重复项,把cursor link 到 next next node 即可;如果不一样,移动cursor到下一个点。
Java Solution:
Runtime beats 18.22%
完成日期:06/09/2017
关键词:singly-linked list
关键点:比较cursor 和 cursor.next,一样就把cursor link 到 next next node。
1 /** 2 * Definition for singly-linked list. 3 * public class ListNode { 4 * int val; 5 * ListNode next; 6 * ListNode(int x) { val = x; } 7 * } 8 */ 9 class Solution 10 { 11 public ListNode deleteDuplicates(ListNode head) 12 { 13 ListNode cursor = head; 14 15 while(cursor != null) 16 { 17 if(cursor.next != null && cursor.val == cursor.next.val) // if find a duplicate one 18 { 19 ListNode duplicate = cursor.next; 20 21 cursor.next = duplicate.next; // link to next next one, skip this duplicate 22 duplicate.next = null; 23 } 24 else 25 cursor = cursor.next; 26 27 } 28 29 return head; 30 } 31 }
参考资料:N/A
LeetCode 题目列表 - LeetCode Questions List
题目来源:https://leetcode.com/