L2-022 重排链表 (25 分)注释详解

#include<bits/stdc++.h>
using namespace std;

const int N = 1e5;

int first,n;


struct per{
	int ads;
	int dt;
	int nx;
};




struct per m[N];
struct per lt[N];
int main(){
	
	cin>>first>>n;
	for(int i=1;i<=n;i++){
		int ads,dt,nx;
		cin>>ads>>dt>>nx;
		
        //记录链表
		m[ads].dt = dt;
		m[ads].nx = nx;
		
		
	}
	
	//cout<<"\n";
	
	int ads = first,cnt = 0;//cnt记录有多少个节点 
	
    //把链表排好  每个节点都有对应的下标cnt
    while(ads != -1){
		lt[cnt].ads = ads;
		lt[cnt].dt = m[ads].dt;
		//cout<<lt[ads].dt<<" ";
		lt[cnt].nx = m[ads].nx;
		ads = m[ads].nx;
		cnt++;
	}
	int j = 0;
	int front = 0;//排好的链表的首部下标
	int tail = cnt-1;//排好的链表的尾部下标
	while (cnt--)
    {
        j++;
        if(j%2==1)//奇数位从后开始遍历
        {
            if(cnt==0)printf("%05d %d -1\n",lt[tail].ads,lt[tail].dt);
            else {
            printf("%05d %d %05d\n",lt[tail].ads,lt[tail].dt,lt[front].ads);
                tail--;
				}
            
        }
        else//偶数位从前开始遍历
        {
            if(cnt==0)printf("%05d %d -1\n",lt[front].ads,lt[front].dt);
            else {
            printf("%05d %d %05d\n",lt[front].ads,lt[front].dt,lt[tail].ads);
                front++;
				}
        }
    }
	
	
	return 0;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值