02-线性结构3 Reversing Linked List (25分)

来源:互联网 发布:免费工程造价软件 编辑:程序博客网 时间:2024/06/05 09:04

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 400000 4 9999900100 1 1230968237 6 -133218 3 0000099999 5 6823712309 2 33218

Sample Output:

00000 4 3321833218 3 1230912309 2 0010000100 1 9999999999 5 6823768237 6 -1

解:主要利用C++的reverse函数,还有C++的cout要格式化输出没有printf方便
C++代码:
#include <iostream>#include <algorithm>#include <vector>#include <stdio.h>using namespace std;#define maxlen 100001struct node{int add;int data;int next;};typedef struct node Node;Node nodes[maxlen];vector<Node> nodeList;int main(){int firstAdd, N, K;cin>>firstAdd>>N>>K;while(N--){Node n;cin>>n.add>>n.data>>n.next;nodes[n.add] = n;}int address = firstAdd;while(address != -1){nodeList.push_back(nodes[address]);address = nodes[address].next;}//到此nodeList存储的就是顺序的列表int len = nodeList.size();int period = len/K;for(int i = 1; i <= period; i++){int head = (i-1)*K;int end = i*K;reverse(nodeList.begin()+head, nodeList.begin()+end);}//reverse complete//print nodeListfor(int i = 0; i < len-1; i++){//cout<<nodeList[i].add<<" "<<nodeList[i].data<<" "<<nodeList[i+1].add<<endl;printf("%05d %d %05d\n", nodeList[i].add, nodeList[i].data, nodeList[i+1].add);}//cout<<nodeList[len-1].add<<" "<<nodeList[len-1].data<<" "<<-1;printf("%05d %d %d\n",nodeList[len-1].add, nodeList[len-1].data, -1);return 0;}

2017-4-16 待续

00000 4 3321833218 3 1230912309 2 0010000100 1 9999999999 5 6823768237 6 -1
0 0
原创粉丝点击