1.主要是考察链表的删除和建表操作,使用map进行记录已经存在过的链表
2.注意是删除绝对值相同的节点
AC代码:
//#include<string>
//#include <iomanip>
#include<vector>
#include <algorithm>
//#include<stack>
#include<set>
#include<queue>
#include<map>
//#include<unordered_set>
#include<unordered_map>
//#include <sstream>
//#include "func.h"
//#include <list>
#include<stdio.h>
#include<iostream>
#include<string>
#include<memory.h>
#include<limits.h>
using namespace std;
/*
00100 5
99999 -7 87654
23854 -15 00000
87654 15 -1
00000 -15 99999
00100 21 23854
00001 2
00002 1 -1
00001 1 00002
*/
struct ListNode{
int val, add;
ListNode* next;
ListNode() :val(-1), add(-1), next(NULL){};
ListNode(int x,int a) :val(x), add(a), next(NULL){};
};
int main(void)
{
ListNode *list = new ListNode[100000];
map<int, bool> exist;
int headAdd, n;
cin >> headAdd >> n;
for (int i = 0; i < n; i++)
{
int pre, val, next;
scanf("%d %d %d", &pre, &val, &next);
list[pre].val = val;
list[pre].add = pre;
if (next != -1)
{
list[next].add = next;
list[pre].next = &list[next];
}
else
list[pre].next = NULL;
}
ListNode*head = &list[headAdd];
ListNode*preHead = head;
ListNode*newList = new ListNode(-1, -1);
ListNode*newListHead = newList;
while (head != NULL)
{
if (exist[abs(head->val)])
{
preHead->next = head->next;
newList->next = head;//
newList = newList->next;//newList现在指向head
head = preHead->next;
newList->next = NULL;
}
else
{
exist[abs(head->val)] = true;
preHead = head;
head = head->next;
}
}
head = &list[headAdd];
while (head != NULL)
{
printf("%05d %d ", head->add, head->val);
if (head->next != NULL)
printf("%05d\n", head->next->add);
else
printf("-1\n");
head = head->next;
}
head = newListHead->next;
while (head != NULL)
{
printf("%05d %d ", head->add, head->val);
if (head->next != NULL)
printf("%05d\n", head->next->add);
else
printf("-1\n");
head = head->next;
}
return 0;
}
本文介绍了一种使用C++实现的链表操作方法,重点在于如何通过map记录已存在的链表节点,并实现删除绝对值相同的节点的功能。该文通过具体代码示例详细解释了链表的构建过程和节点删除的具体实现。
948

被折叠的 条评论
为什么被折叠?



