编写代码,移除未排序链表中的重复节点。保留最开始出现的节点。

    1. 示例1
    2. 输入:[1,2,3,3,2,1]
    3. 输出:[1,2,3]
    4. 输入:[1,1,1,1,2]
    5. 输出:[1,2]

    提示:

    1. 链表长度在 [0,20000] 范围内。
    2. 链表元素在 [0,20000] 范围内。

    使用哈希表,将存在的元素加入到哈希集合 HashSet 中,然后依次比较每个元素,如果该元素存在哈希集合中,则忽略,否则加入到哈希集合中。

    1. /**
    2. * Definition for singly-linked list.
    3. * struct ListNode {
    4. * int val;
    5. * struct ListNode *next;
    6. * };
    7. */
    8. struct ListNode* removeDuplicateNodes(struct ListNode* head){
    9. if (head == NULL) return head;
    10. int *arr = (int *)calloc(20001,sizeof(int));
    11. arr[head->val] = 1;
    12. struct ListNode *pos = head;
    13. while (pos->next != NULL) {
    14. struct ListNode *cur = pos->next;
    15. if (arr[cur->val] == 1) {
    16. pos->next = pos->next->next;
    17. } else {
    18. arr[cur->val] = 1;
    19. pos = pos->next;
    20. }
    21. }
    22. pos->next = NULL;
    23. return head;
    24. }