码迷,mamicode.com
首页 > 其他好文 > 详细

1074 Reversing Linked List (25 分)

时间:2019-01-28 01:05:58      阅读:118      评论:0      收藏:0      [点我收藏+]

标签:ensure   ddr   scanf   node   hit   length   +=   example   lin   

1074 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

#include<iostream>
#include<vector>
#include<algorithm>
#include<queue>
#include<string>
#include<map>
#include<set>
#include<stack>
#include<string.h>
#include<cstdio>
#include <unordered_map>
#include<cmath>

using namespace std;
struct Node
{
    int address,data,next;
};

int main()
{
    int head,n,k;
    scanf("%d%d%d",&head,&n,&k);
    map<int,Node> mp;
    //Node temp;
    int a,b,c;
    for(int i=0;i<n;i++)
    {
        scanf("%d%d%d",&a,&b,&c);
        mp[a]={a,b,c};
    }
    vector<Node>node;
    for(int i=head;i!=-1;i=mp[i].next)
        node.push_back(mp[i]);
    int len=node.size();
    for(int i=0;i<len;i+=k)
    {
        if(len-i<k)
            break;
        int temp=1;
        for(int j=i;j<(i+i+k)/2;j++)
        {
            swap(node[j],node[i+k-temp]);
            temp++;
        }

    }
    for(int i=0;i<len-1;i++)
    {
        printf("%05d %d %05d\n",node[i].address,node[i].data,node[i+1].address);
    }
    printf("%05d %d -1\n",node[len-1].address,node[len-1].data);
    return 0;
}

 

1074 Reversing Linked List (25 分)

标签:ensure   ddr   scanf   node   hit   length   +=   example   lin   

原文地址:https://www.cnblogs.com/zhanghaijie/p/10327740.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!