Skip to content

Commit 9fdf2f4

Browse files
author
Kai Yang
committed
83. Remove Duplicates from Sorted List
1 parent 06a39da commit 9fdf2f4

File tree

2 files changed

+85
-0
lines changed

2 files changed

+85
-0
lines changed
Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
using System;
2+
using System.Collections.Generic;
3+
using System.Linq;
4+
using Newtonsoft.Json;
5+
using NUnit.Framework;
6+
7+
public class ListNode {
8+
public int val;
9+
public ListNode next;
10+
public ListNode(int x) { val = x; }
11+
}
12+
13+
[TestFixture]
14+
public class TestClass
15+
{
16+
private static Random _random = new Random();
17+
18+
[TestCase(10, 10, 1000)]
19+
public void TestMethod(int maxLength, int maxValue, int repeatTimes)
20+
{
21+
for (var r = 0; r < repeatTimes; ++r)
22+
{
23+
var length = _random.Next(maxLength + 1);
24+
var listValues = new int[length];
25+
for (var i = 0; i < length; ++i)
26+
{
27+
listValues[i] = _random.Next(i == 0 ? 0 : listValues[i - 1], maxValue + 1);
28+
}
29+
30+
var head = GetHead(listValues);
31+
var result = new Solution().DeleteDuplicates(head);
32+
Assert.AreEqual(JsonConvert.SerializeObject(listValues.Distinct()), JsonConvert.SerializeObject(GetList(result)), JsonConvert.SerializeObject(listValues));
33+
}
34+
}
35+
36+
private ListNode GetHead(int[] values)
37+
{
38+
ListNode head = null;
39+
ListNode current = null;
40+
foreach (var val in values)
41+
{
42+
if (head == null)
43+
{
44+
head = new ListNode(val);
45+
current = head;
46+
}
47+
else
48+
{
49+
current.next = new ListNode(val);
50+
current = current.next;
51+
}
52+
}
53+
return head;
54+
}
55+
56+
private IEnumerable<int> GetList(ListNode head)
57+
{
58+
while (head != null)
59+
{
60+
yield return head.val;
61+
head = head.next;
62+
}
63+
}
64+
}

83.RemoveDuplicatesFromSortedList.cs

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
public class Solution {
2+
public ListNode DeleteDuplicates(ListNode head) {
3+
if (head == null) return null;
4+
var last = head;
5+
var current = head.next;
6+
while (current != null)
7+
{
8+
if (current.val != last.val)
9+
{
10+
last.next = current;
11+
last = current;
12+
}
13+
else
14+
{
15+
last.next = null;
16+
}
17+
current = current.next;
18+
}
19+
return head;
20+
}
21+
}

0 commit comments

Comments
 (0)