[数据结构]02-线性结构3 Reversing Linked List

Given a constant KK and a singly linked list LL, you are supposed to reverse the links of every KK elements on LL. For example, given LL being 1→2→3→4→5→6, if K = 3K=3, then you must output 3→2→1→6→5→4; if K = 4K=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 NN (\le 10^5105) which is the total number of nodes, and a positive KK (\le NN) 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 NN 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 Nextis 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


#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define size 100004
int data[size];
int next[size];
typedef struct ma *Prt;
typedef struct ma {
	int addr;
	int data;
	int nextaddr;
	Prt next;
}Node;
//typedef struct ma Node;
Node ar[size];

Prt listReverse(Prt head, int k);
void PrintPrt(Prt a);
int main(void)
{
	int firstAddr;
	int N;
	int k;
	int num = 0;

	int temp;
	scanf("%d %d %d", &firstAddr, &N, &k);
	

	ar[0].nextaddr = firstAddr;

	for (int i = 0; i < N; i++)
	{
		scanf("%d", &temp);
		scanf("%d %d", &data[temp], &next[temp]);
	}

	int i = 1;
	while (1)
	{
		if (ar[i-1].nextaddr==-1)
		{
			ar[i - 1].next = NULL;
			num = i - 1;
			break;
		}
		
		ar[i].addr = ar[i - 1].nextaddr;
		ar[i].data = data[ar[i].addr];
		ar[i].nextaddr = next[ar[i].addr];
		ar[i - 1].next = ar + i;
		
		i++;

	}
	Prt p = ar;
	Prt rp = NULL;

	for (int i = 0; i < (num / k); i++)
	{
		rp = listReverse(p, k);
		p->next = rp;
		p->nextaddr = rp->addr;
		
		int j=0;
		while (j < k)
		{
			p = p->next;
			j++;
		}
	}

	PrintPrt(ar);


	return 0;
}

Prt listReverse(Prt head, int k)
{
	int count = 1;
	Prt new = head->next;
	Prt old = new->next;
	Prt temp = NULL;

	while (count < k)
	{
		temp = old->next;
		old->next = new;
		old->nextaddr = new->addr;
		new = old;
		old = temp;

		count++;
	}
	head->next->next = old;
	if (old != NULL)
	{
		head->next->nextaddr = old->addr;
	}
	else
	{
		head->next->nextaddr = -1;
	}
	return new;
}

void PrintPrt(Prt a)
{
	Prt p = a->next;

	while (p)
	{
		if (p->nextaddr != -1)
		{
			printf("%05d %d %05d\n", p->addr,p->data, p->nextaddr);
		}
		else
		{
			printf("%05d %d %d\n", p->addr, p->data, p->nextaddr);
		}
		p = p->next;
	}
}




猜你喜欢

转载自blog.csdn.net/sinat_37273780/article/details/64934722