给定一个排序链表,删除所有重复的元素,使得每个元素只出现一次。
示例 1:
输入: 1->1->2 输出: 1->2
示例 2:
输入: 1->1->2->3->3 输出: 1->2->3
虽然对链表不熟悉,第一反应就是用hashSet<int>
如果是 1 -2-2-4-1
HashSet<int> set = new HashSet<int>();
while (head!=null)
{
set.Add(int.Parse(head.val.ToString()));
head = head.next;
}
求出了 set =[1,2,4] 那么问题来了?怎么把这串数字放到链表 ?
哦! 似乎题是排序的,所以不需要考虑这些。
那么需要用到指针:
/**
* Definition for singly-linked list.
* public class ListNode {
* public int val;
* public ListNode next;
* public ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode DeleteDuplicates(ListNode head) {
ListNode current = head;
while (current!=null&¤t.next!=null)
{
if (current.next.val==current.val)
{
current.next = current.next.next;//这样就把相等的这个给过掉(删除)
}
else
{
current = current.next;//下一个
}
}
return head;
}
}
请问为什么 整个过程都未对head进行操作,但最后还是return head?