题目为 编写代码,移除未排序链表中的重复节点。保留最开始出现的节点。
思路为根据键值对判断是否重复,记录上一个节点,如果重复,则将节点的下一节点设置为空,直至不重复为止。代码如下
public ListNode RemoveDuplicateNodes(ListNode head)
{
ListNode li2 = null;
ListNode now = head;
Dictionary<int, int> dic = new Dictionary<int, int>();
while (now != null)
{
if (!dic.ContainsKey(now.val))
{
dic.Add(now.val,1);
if (li2!=null)
{
li2.next = now;
}
li2 = now;
now = now.next;
}
else
{
now = now.next;
li2.next = null;
}
}
return head;
}