LeetCode Online Judge 题目C# 练习 - Remove Duplicates from Sorted List II

本文介绍如何在保持链表排序的情况下,移除所有重复的节点,仅保留唯一值。通过创建虚拟头节点和遍历链表实现,确保代码简洁且易于理解。

Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.

For example,

Given 1->2->3->3->4->4->5, return 1->2->5.
Given 1->1->1->2->3, return 2->3.

 1         public static LinkedListNode RemoveDuplicatesfromSortedListIIOpt(LinkedListNode head)
 2         {
 3             if (head == null || head.Next == null)
 4                 return head;
 5 
 6             LinkedListNode fakeHead = new LinkedListNode();
 7             LinkedListNode prev = fakeHead;
 8             prev.Next = head;
 9             LinkedListNode curr = head;
10 
11             while (curr != null && curr.Next != null)
12             {
13                 //curr Node has duplicated
14                 if ((int)curr.Value == (int)curr.Next.Value)
15                 {
16                     //find the next Node, which value != curr.value
17                     int temp = (int)curr.Value;
18                     curr = curr.Next;
19                     while (curr != null && (int)curr.Value == temp)
20                     {
21                         curr = curr.Next;
22                     }
23                     prev.Next = curr;
24                 }
25                 //curr Node has no duplicated
26                 else
27                 {
28                     prev = prev.Next;
29                     curr = curr.Next;
30                 }
31             }
32 
33             return fakeHead.Next;
34         }

代码分析:

  这一题稍稍有点tricky。我还是创建了一个fakeNode,用来连接head,返回的时候返回fakeHead.Next, 这样下面的逻辑就适合所有的Node了,而不用去特殊处理第一个Node就有duplicate 的 corner case。

  这种题虽然是BF,没什么好复习的,但是还是要小心再小心,不容易写出BUG FREE的CODE。

转载于:https://www.cnblogs.com/etcow/archive/2012/10/12/2720698.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值