您的位置:首页 > 其它

1097. Deduplication on a Linked List (25)

2015-11-22 10:02 417 查看
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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: