题目描述:给定一个排序链表,删除所有重复的元素,使得每个元素只出现一次。
示例 1:
输入: 1->1->2
输出: 1->2
- 双指针遍历:使用两个指针分别指向当前结点和当前结点的前一个结点,方便删除操作
//C struct ListNode* deleteDuplicates(struct ListNode* head){ //注意这里对head是否为空的判断 if(head == NULL || head -> next == NULL) return head; struct ListNode *pre, *cur; pre = head; cur = head -> next; while(cur != NULL){ if(pre -> val == cur -> val){ struct ListNode *p; pre -> next = cur -> next; p = cur; free(p); cur = pre -> next; } else{ pre = pre -> next; cur = cur -> next; } } return head; }
- 单指针遍历:
//JS var deleteDuplicates = function(head) { let cur = head; while(cur && cur.next){ if(cur.val == cur.next.val){ cur.next = cur.next.next; } else{ cur = cur.next; } } return head; };
- 哈希表或者Map记录出现过的结点元素:这里新建了一个头结点,方便遍历
//JS var deleteDuplicates = function(head) { let hash = new Map(), p = head; let Lhead = new ListNode(); let q = Lhead; Lhead.next = head; while(p){ if(hash.has(p.val)) { q.next = p.next; } else { hash.set(p.val, 1); q = q.next; } p = p.next; } p = Lhead.next; Lhead = null; return p; };