【题目来源】
2015年全国硕士研究生招生考试题:https://www.acwing.com/problem/content/3759/
【题目描述】
一个单链表中有 m 个结点,每个结点上的元素的绝对值不超过 n。
现在,对于链表中元素的绝对值相等的结点,仅保留第一次出现的结点而删除其余绝对值相等的结点。
请输出筛选后的新链表。
例如,单链表 21 -> -15 -> -15 -> -7 -> 15,在进行筛选和删除后,变为 21 -> -15 -> -7。
【输入样例】
输入:21->-15->-15->-7->15
【输出样例】
输出:21->-15->-7
【数据范围】
1≤m≤1000,
1≤n≤10000
【算法分析】
★ 本题采用核心代码模式提交:https://blog.csdn.net/hnjzsyjyj/article/details/141950102
★ free 用于释放动态分配的内存,而 delete 用于释放通过 new 操作符分配的内存。
【算法代码】
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
int st[10005];
typedef struct ListNode* Node;
class Solution {
public:
ListNode* filterList(ListNode* head) {
st[abs(head->val)]=1;
Node p=head;
while(p->next) {
if(st[abs(p->next->val)]) {
Node q=p->next;
p->next=q->next;
//free(q);
} else {
p=p->next;
st[abs(p->val)]=1;
}
}
return head;
}
};
【参考文献】
https://blog.csdn.net/hnjzsyjyj/article/details/132185463
https://blog.csdn.net/hnjzsyjyj/article/details/134918044
https://www.acwing.com/solution/content/72794/
https://blog.csdn.net/hnjzsyjyj/article/details/141950102