PAT2019秋7-2 Merging Linked Lists (25 分)

Given two singly linked lists L​1​​=a​1​​→a​2​​→⋯→a​n−1​​→a​n​​ and L​2​​=b​1​​→b​2​​→⋯→b​m−1​​→b​m​​. If n≥2m, you are supposed to reverse and merge the shorter one into the longer one to obtain a list like a​1​​→a​2​​→b​m​​→a​3​​→a​4​​→b​m−1​​⋯. For example, given one list being 6→7 and the other one 1→2→3→4→5, you must output 1→2→7→3→4→6→5.

Input Specification:

Each input file contains one test case. For each case, the first line contains the two addresses of the first nodes of L​1​​ and L​2​​, plus a positive N (≤10​^5​​) which is the total number of nodes given. 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 a positive integer no more than 10​5​​, and Next is the position of the next node. It is guaranteed that no list is empty, and the longer list is at least twice as long as the shorter one.

Output Specification:

For each case, output in order the resulting linked list. Each node occupies a line, and is printed in the same format as in the input.

思路

采用静态链表的方法,把结点存到node数组里,再用循环把全部按链表的顺序存到vector里(重要!!!)。比较两个链表的大小,把小的链表放到v2里,再翻转v2。再把v1和v2里的数放到v3里,每3个数放一次v2的数。最后输出,要注意最后一位的next是-1,并且不足5位数的前面需要补0.

代码

#include<stdio.h>
#include<vector>
#include<algorithm>
using namespace std;
struct Node{
	int data,next;
}node[100005];
vector<int> v1,v2,v3;
int main(){
	int h1,h2,n,t;
	scanf("%d%d%d",&h1,&h2,&n);
	for(int i=0;i<n;i++){
		scanf("%d",&t);
		scanf("%d%d",&node[t].data,&node[t].next);
	}
	//按链表顺序存入vector 
	for(int p=h1;p!=-1;p=node[p].next)
		v1.push_back(p);
	for(int p=h2;p!=-1;p=node[p].next)
		v2.push_back(p); 
	if(v1.size()<v2.size())//把更长的链表放到v1 
		swap(v1,v2);
	reverse(v2.begin(),v2.end());
	for(int i=0,j=0,k=0;i<v1.size()||j<v2.size();k++){
		if((k+1)%3==0&&j<v2.size())
			v3.push_back(v2[j++]);
		else
			v3.push_back(v1[i++]);
	}
	for(int i=0;i<v3.size();i++){
		if(i==v3.size()-1) printf("%05d %d -1\n",v3[i],node[v3[i]]); 
		else printf("%05d %d %05d\n",v3[i],node[v3[i]],v3[i+1]); 
	}
}

 

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值