02-線性結構3 Reversing Linked List (25 分)

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 (≤10​5​​) 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

這道題一開始沒能想到開List數組記錄順序。這個方法以後應該要記住。嗯。

另外就是#include<algorithm>中的reverse函數,是翻轉a[i]到a[i+j]之間的數組。[a[i], a[i+j] )

最後一個評分點,需要考慮到輸入的節點不在鏈表的情況。不能夠直接用輸入的節點數量N。

#include<iostream>
#include<algorithm>
using namespace std;
struct node{
	//	int Address; 
		int Num;
		int Next;
	};
node add[100001];
int List[100001];
//typedef struct node *List;
void Reverse(node &a, node &b);

int main(){

	int InitialAddress;
	int N,K,t1,n;
	int i;
    int address;
	cin>>InitialAddress>>N>>K;
	n=N;
	while(n--){
		cin>>t1;
		cin>>add[t1].Num>>add[t1].Next;
	}
	n=N;
	address = InitialAddress;
	i = 0;
	List[i] = InitialAddress; 
	i++;
	while(add[address].Next!=-1){
		List[i] = add[address].Next;
		address = add[address].Next;
		i++;
	}
	List[i] = add[address].Next;
    N = i;
	i = 0;
	while(i+K<=N){
		reverse(&List[i],&List[i+K]); //reverse函數,翻轉List[i]到List[i+k]之間的所有數組(將其視爲統一的整體翻轉) 
		i = i + K;
	}
	
	for(i=0;i<N;i++){
    	//cout<<List[i]<<endl;
    	printf("%05d %d ",List[i],add[List[i]].Num);
    	if(List[i+1]!=-1){
    		printf("%05d\n",List[i+1]);
		}
		else{
			printf("-1\n");
		}
    	
	}
	return 0;
} 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章