LeetCode 面试题 02.01. 移除重复节点

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

示例1:

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

输入:[1, 1, 1, 1, 2]
输出:[1, 2]
提示:

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

 1 /**
 2  * Definition for singly-linked list.
 3  * struct ListNode {
 4  *     int val;
 5  *     struct ListNode *next;
 6  * };
 7  */
 8 
 9 struct ListNode* removeDuplicateNodes(struct ListNode* head){
10     if(head==NULL||head->next==NULL) return head;
11     int index[20005]={0};
12     index[head->val]=1;
13     struct ListNode *pre=head,*q=head->next;
14     while(q){
15         if(index[q->val]==0){
16             index[q->val]=1;
17             pre=q;
18             q=q->next;
19         }else{
20             pre->next=q->next;
21             q=pre->next;
22         }
23     }
24     return head;
25 }

 

posted @ 2020-02-27 17:25  wydxry  阅读(445)  评论(0编辑  收藏  举报
Live2D