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。

 /**
* 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 cursor = head; while(cursor != null)
{
if(cursor.next != null && cursor.val == cursor.next.val) // if find a duplicate one
{
ListNode duplicate = cursor.next; cursor.next = duplicate.next; // link to next next one, skip this duplicate
duplicate.next = null;
}
else
cursor = cursor.next; } return head;
}
}

参考资料:N/A

LeetCode 题目列表 - LeetCode Questions List

题目来源:https://leetcode.com/

04-28 08:37