您的位置:首页 > 其它

PAT天坑之1074. Reversing Linked List (25)

2017-04-15 15:25 459 查看
Given a constant K and a singly linked list L, you are supposed to reverse the links of every K elements on L. For example, given L being 1→2→3→4→5→6, if K = 3, then you must output 3→2→1→6→5→4; if K = 4, you must output 4→3→2→1→5→6.

Input Specification:

Each input file contains one test case. For each case, the first line contains the address of the first node, a positive N (<= 105) which is the total number of nodes, and a positive K (<=N) which is the length of the sublist to be reversed. The address of a node is a 5-digit nonnegative integer, and NULL is represented by -1.

Then N lines follow, each describes a node in the format:

Address Data Next

where Address is the position of the node, Data is an integer, and Next is the position of the next node.

Output Specification:

For each case, output the resulting ordered linked list. Each node occupies a line, and is printed in the same format as in the input.

Sample Input:

00100 6 4

00000 4 99999

00100 1 12309

68237 6 -1

33218 3 00000

99999 5 68237

12309 2 33218

Sample Output:

00000 4 33218

33218 3 12309

12309 2 00100

00100 1 99999

99999 5 68237

68237 6 -1

此题思路用数组模拟链表。

1.构建链表:

用map《int,listnode> 来映射每个地址所对应的节点。

从头结点开始,利用查询map来将链表的下一个节点存入数组lists。此时数组中的节点都是有序连接的。

2.翻转链表:

利用栈,每次压入数组中的K个节点,再弹出来替代原节点

这个思路的时间复杂度是O(KN),时间复杂度也不好,但是对于题目要求而言是完全够用了,

前方高能预警!!!!

提交后发现最后一个点不过!!!!

结果发现原来,headadress不一定是链表中第一个头节点,链表中存在无效节点,从头地址开始到-1,除此之外的都是废节点。题目也没说。。

#include <vector>
#include <iostream>
#include <stdlib.h>
#include <stack>
#include <string>
#include <algorithm>
#include <map>
#include <set>
#include <time.h>
#include <queue>
#include <functional>
#include <cstdio>
#include <sstream>
#include<iomanip>
using namespace std;
using namespace std;
struct siglelist
{
int adress;
int value;
int next;
};

int main()
{
map<int, siglelist> nextindex;
int headadress, n, k;
siglelist lists[100000];
cin >> headadress >> n >> k;
for (int i = 0; i < n; i++)
{
//  scanf("%d%d%d", &lists[i].adress, lists[i].value, lists[i].next);
cin >> lists[i].adress >> lists[i].value >> lists[i].next;
nextindex[lists[i].adress] = lists[i];
}
lists[0] = nextindex[headadress];
for (int i = 1; i < n; i++)
{
if(lists[i - 1].next!=-1) lists[i] = nextindex[lists[i - 1].next];
else
{
n = i;
break;
}
}
stack<siglelist> lstack;
int j = 0;
while (j<n)
{
int l = j;
if (l + k > n) break;
while (j < n &&j <(l + k)) lstack.push(lists[j++]);
while (lstack.size()>0)
{
lists[l++] = lstack.top();
lstack.pop();
}
}
for (int i = 0; i < n; i++)
{
if(i<n-1) printf("%05d %d %05d\n", lists[i].adress, lists[i].value, lists[i + 1].adress);
else printf("%05d %d -1\n", lists[i].adress, lists[i].value);
}
return 0;
}


不过后来看大牛的题解发现优化后有更好的方法,细节上有很大的提升空间。

1.listnode结构体中只需要有adress和val就够了;

2.用数组map[100000][2]来表示地址与val以及下一个节点地址的关系,查找只需O(1);

3.通过数组将节点有序存入vector,再调用reserve来翻转。

当然主要是数组代替map,效率会提高,事实上vector也很慢。。。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: