编写代码,移除未排序链表中的重复节点。保留最开始出现的节点。
示例1输入:[1,2,3,3,2,1]输出:[1,2,3]输入:[1,1,1,1,2]输出:[1,2]
提示:
- 链表长度在
[0,20000]范围内。 - 链表元素在
[0,20000]范围内。
使用哈希表,将存在的元素加入到哈希集合 HashSet 中,然后依次比较每个元素,如果该元素存在哈希集合中,则忽略,否则加入到哈希集合中。
/*** Definition for singly-linked list.* struct ListNode {* int val;* struct ListNode *next;* };*/struct ListNode* removeDuplicateNodes(struct ListNode* head){if (head == NULL) return head;int *arr = (int *)calloc(20001,sizeof(int));arr[head->val] = 1;struct ListNode *pos = head;while (pos->next != NULL) {struct ListNode *cur = pos->next;if (arr[cur->val] == 1) {pos->next = pos->next->next;} else {arr[cur->val] = 1;pos = pos->next;}}pos->next = NULL;return head;}
