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

Reversing Linked List

时间:2015-10-11 21:32:52      阅读:250      评论:0      收藏:0      [点我收藏+]

标签:

 

  题目来源PTA02-线性结构2 Reversing Linked List   (25分)

  Question: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 (≤105) 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

 

  Show the code:

#include<iostream>
#include<algorithm>    //使用algorithm的reverse函数进行反转
using namespace std;

const int MaxSize = 100000+10;

struct LinkNode        //节点,因为给出了地址值,用顺序表比用链表方便
{
    int data;
    int next;

}Node[MaxSize];

int List[MaxSize];    //顺序表地址

int main()
{
    int FirstAddr,N,K;   //N是输入的节点数,但这些节点不一定首尾相连都在顺序表上
    cin>>FirstAddr>>N>>K;//输入第一行
    int Address,Data,Next,i;
    for(i=0;i<N;i++)
    {
        cin>>Address>>Data>>Next;
        Node[Address].data = Data;
        Node[Address].next = Next;
    }
    int List_n=0;       //能首尾相连在顺序表上的节点数
    int p=FirstAddr;    //p指示当前节点
    while(p!=-1)        
    {
        List[List_n++] = p;
        p = Node[p].next;
    }
    i=0;
    while(i+K<=List_n)
    {
        reverse(&List[i],&List[i+K]);//Reverses the order of the elements in the range [first,last)
        i=i+K;
    }
    for (i = 0;i < List_n-1;i++)    //输出逆转后的顺序表
    {
        printf("%05d %d %05d\n", List[i], Node[List[i]].data, List[i+1]);//%05d为输出5位整数,不足在前面补0
    }
    printf("%05d %d -1\n", List[i], Node[List[i]].data);    //输出逆转后的顺序表的最后一项
    return 0;
} 

 

Reversing Linked List

标签:

原文地址:http://www.cnblogs.com/eniac12/p/4870035.html

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