PAT1025 反转链表 (25分)(C++语言)

在这里插入图片描述

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

思路:
一个简单的反转操作,直接自己代码模拟也可。用STL库的reverse()函数会较为简单。
代码

#include<iostream>
#include<stdlib.h> 
#include<algorithm>
using namespace std;


int main()
{
	int start;
	int list[100000];
	int data[100000];
	int next[100000]; 
	int sum;
	int fan;
	cin>>start>>sum>>fan;
	int i;
	int addr;
	for(i=0;i<sum;i++){
		cin>>addr;
		cin>>data[addr]>>next[addr];
	}
	int k=0;
	for(i=0;start!=-1;i++){
		list[i]=start;
		start=next[start];
		k++;
	}
	for(i=0;i<k/fan;i++){
		reverse(list+i*fan,list+(i+1)*fan);
	}
	for(i=0;i<k;i++){
		if(i==k-1){
			printf("%05d %d -1\n",list[i],data[list[i]]);
		}
		else{
			printf("%05d %d %05d\n",list[i],data[list[i]],list[i + 1]);
		}
	} 
	system("pause");
	return 0;
}
发布了161 篇原创文章 · 获赞 7 · 访问量 7112

猜你喜欢

转载自blog.csdn.net/weixin_43778744/article/details/103929137