題目爲 編寫代碼,移除未排序鏈表中的重複節點。保留最開始出現的節點。
思路爲根據鍵值對判斷是否重複,記錄上一個節點,如果重複,則將節點的下一節點設置爲空,直至不重複爲止。代碼如下
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;
}