I am learning algorithms. And my current algorithm is create a single list, and try to remove all duplicated elements in a sorted list. Ex: given Input: 1 -> 1 -> 1 -> 2 -> 2 -> 3 -> 5 -> 5 -> 7 Expected Output: 3 -> 7
My bellow solution worked well:
//Definition for singly-linked list.
public class ListNode
{
public int val;
public ListNode next;
public ListNode(int x)
{
val = x;
next = null;
}
}
public ListNode deleteAllDuplicates(ListNode list)
{
if (list == null)
{
return null;
}
var start = list;
var isStart = true;
var pre = start;
var tmp = list.val;
while (list?.next != null)
{
if (tmp == list.next.val)
{
while (list?.val == tmp)
{
list = list.next;
}
if (isStart)
{
start = list;
pre = start;
}
else
{
pre.next = list;
}
if (list == null)
{
return start;
}
tmp = list.val;
}
else
{
pre = list;
list = list.next;
tmp = list.val;
isStart = false;
}
}
return start;
}
My question is: What should I do to improve the solution? Any help are appriciate!
A
is really a terrible variable name. I'm sure you can think of something more meaningful. \$\endgroup\$ – t3chb0t Oct 11 '18 at 10:13ListNode
is gone ;-P \$\endgroup\$ – t3chb0t Oct 11 '18 at 10:41[1, 2, 1]
. If this is only intended to work with sorted inputs then you may want to explicitly say so. \$\endgroup\$ – Pieter Witvoet Oct 11 '18 at 12:50