1025. Reverse Linked List

topic here


A linked list may not necessarily be written in a linked list, but all data can be stored in an array. Then put the array with respect to the positions in order, so that you only need to move the position of the array.


#include <iostream>
#include <bits/stdc++.h>
using namespace std;

struct node {
	int data;
	int next;
};

intmain()
{
	struct node s[100001];
	int n, m;
	int add;
	cin >> add >> n >> m;
	int address[100001];
	for(int i = 0; i < n; i++) {
		int num;
		cin >> num;
		cin >> s[num].data >> s[num].next;
	}
	int k = 0;
	while(add != -1) {
		address[k++] = add;
		add = s[add].next;
	}

	for(int i = 0; i < k / m; i++) {
		for(int j = 0; j < m / 2; j++) {
			swap(address[j + m * i], address[i * m + m - 1 - j]);
		}
	}
	for(int i = 0; i < k; i++) {
		if(i != k - 1) {
			printf("%05d %d %05d\n", address[i], s[address[i]].data, address[i + 1]);	
		} else {
			printf("%05d %d -1\n", address[i], s[address[i]].data);
		}
	}
	return 0;
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325733486&siteId=291194637