PAT乙级 1025.反转链表

#include<iostream>
#include<stack>
#include<algorithm>
#include<cmath>
#include<cstdio>
using namespace std;
struct node
{
    int data;
    int next;
}list1[1001000];
stack<int> p1,p2;
int main()
{
    int start,n,k,a;
    scanf("%d%d%d",&start,&n,&k);
    for(int i=0;i<n;i++)
    {
        scanf("%d",&a);
        scanf("%d%d",&list1[a].data,&list1[a].next);
    }
    if(start==-1)
    {
        cout<<-1<<endl;
        return 0;
    }
    int p=start,z=0,flag=0;
    while(p!=-1)
    {
        p1.push(p);
        z++;
        if(z%k==0)
        {
            while(!p1.empty())
            {
                int t1=p1.top();
                if(flag==0)
                {
                    flag=1;
                    printf("%05d %d ",t1,list1[t1].data);
                }
                else
                    printf("%05d\n%05d %d ",t1,t1,list1[t1].data);
                p1.pop();
            }
        }
        p=list1[p].next;
    }
    if(z%k==0)
        printf("%d",-1);
    else
    {
        while(!p1.empty())
        {
            int t1=p1.top();
            p2.push(t1);
            p1.pop();
        }
        while(!p2.empty())
        {
            int t1=p2.top();
            printf("%05d\n%05d %d ",t1,t1,list1[t1].data);
            p2.pop();
        }
        printf("%d",-1);
    }
    return 0;
}

发布了45 篇原创文章 · 获赞 1 · 访问量 6781

猜你喜欢

转载自blog.csdn.net/Ls_attack/article/details/79797925
今日推荐