您的位置:首页 > 其它

1025. 反转链表 (25)--做题记录

2016-07-31 00:39 585 查看

1025. 反转链表 (25)

给定一个常数K以及一个单链表L,请编写程序将L中每K个结点反转。例如:给定L为1→2→3→4→5→6,K为3,则输出应该为3→2→1→6→5→4;如果K为4,则输出应该为4→3→2→1→5→6,即最后不到K个元素不反转。

输入格式:

每个输入包含1个测试用例。每个测试用例第1行给出第1个结点的地址、结点总个数正整数N(<= 105)、以及正整数K(<=N),即要求反转的子链结点的个数。结点的地址是5位非负整数,NULL地址用-1表示。

接下来有N行,每行格式为:

Address Data Next

其中Address是结点地址,Data是该结点保存的整数数据,Next是下一结点的地址。

输出格式:

对每个测试用例,顺序输出反转后的链表,其上每个结点占一行,格式与输入相同。

输入样例:
00100 6 4
00000 4 99999
00100 1 12309
68237 6 -1
33218 3 00000
99999 5 68237
12309 2 33218

输出样例:
00000 4 33218
33218 3 12309
12309 2 00100
00100 1 99999
99999 5 68237
68237 6 -1
#include <iostream>
#include <map>
#include <stack>
using namespace std;

void appendZero(int data) {
if (data < 10) {
printf("0000%d",data);
}else if (data < 100) {
printf("000%d",data);
}else if (data < 1000) {
printf("00%d",data);
}else if (data < 10000) {
printf("0%d",data);
}else {
printf("%d",data);
}
}

int main() {

map<int, int>valueMap, nextMap;

int begin, N, K;
cin>>begin>>N>>K;

//cout<<begin<<" "<<N<<" "<<K;
int i = 0;
for (i = 0; i < N; i++) {
int address, data, next;
cin>>address>>data>>next;
valueMap.insert(pair<int, int>(address, data));
nextMap.insert(pair<int, int>(address, next));
}

//cout<<"-----------------------------------"<<endl;

stack<int> s1;

int count = 0, index = begin, waitToPrintNext = 0;
while(true) {

// 计数
count++;

// 压栈
s1.push(index);

if (count == K) {
for (i = 0; i < K; i++){

if (i == 0 && waitToPrintNext == 1) {
appendZero(s1.top());
printf("\n");
waitToPrintNext = 0;
}

appendZero(s1.top());
printf(" %d ", valueMap[s1.top()]);
s1.pop();

if (i != K - 1) {
appendZero(s1.top());
printf("\n");
}
}
count = 0;
waitToPrintNext = 1;
}

// index 后移
index = nextMap[index];

if (index == -1) {
if (s1.size() == 0) {
printf("-1\n");
}
break;
}
}

// 余下结尾

stack<int> s2;

while (s1.size() > 0){
s2.push(s1.top());
s1.pop();
}

i=0;
while (s2.size() > 0){
if (i==0&&waitToPrintNext==1) {
appendZero(s2.top());
printf("\n");
i++;
}

appendZero(s2.top());
printf(" %d ", valueMap[s2.top()]);
if (s2.size() != 1) {
appendZero(nextMap[s2.top()]);
}else {
printf("-1");
}
printf("\n");
s2.pop();
}

return 0;
}

 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  PAT