重排链表

7-9 重排链表 (25 分)
给定一个单链表 L
​1
​​ →L
​2
​​ →⋯→L
​n−1
​​ →L
​n
​​ ,请编写程序将链表重新排列为 L
​n
​​ →L
​1
​​ →L
​n−1
​​ →L
​2
​​ →⋯。例如:给定L为1→2→3→4→5→6,则输出应该为6→1→5→2→4→3。

输入格式:
每个输入包含1个测试用例。每个测试用例第1行给出第1个结点的地址和结点总个数,即正整数N (≤10
​5
​​ )。结点的地址是5位非负整数,NULL地址用−1表示。

接下来有N行,每行格式为:

Address Data Next
其中Address是结点地址;Data是该结点保存的数据,为不超过10
​5
​​ 的正整数;Next是下一结点的地址。题目保证给出的链表上至少有两个结点。

输出格式:
对每个测试用例,顺序输出重排后的结果链表,其上每个结点占一行,格式与输入相同。

输入样例:
00100 6
00000 4 99999
00100 1 12309
68237 6 -1
33218 3 00000
99999 5 68237
12309 2 33218
输出样例:
68237 6 00100
00100 1 99999
99999 5 12309
12309 2 00000
00000 4 33218
33218 3 -1

#include<iostream>
#include<string>

using namespace std;

struct Card
{
	string add;
	int data;
	string next;
};
struct Card list[100000];
struct Card relist[100000];

int main()
{
	string head;
	int n;
	cin >> head >> n;
	for (int i = 0; i < n; i++)
		cin >> list[i].add >> list[i].data >> list[i].next;
	string k = head;
	for (int j = 0; j < n; j++)
	{
		for (int i = 0; i < n; i++)
		{
			if (k == list[i].add)
			{
				relist[j] = list[i], k = list[i].next;
				break;
			}
		}
	}
	int i = 0, j = n - 1;
	int t = 0;
	while (i < j)
	{
		list[t++] = relist[j--];
		list[t++] = relist[i++];
	}
	if (i == j)
	{
		list[t] = relist[i];
	}
	for (int i = 0; i < 5; i++)
		list[i].next = list[i + 1].add;
	list[n - 1].next = "-1";
	for (int i = 0; i < n; i++)
		cout << list[i].add << " " << list[i].data << " " << list[i].next << endl;
}
重排链表的python实现可以使用栈来实现。首先,将链表中的节点压入栈中,然后按照指定的规则依次从栈中出栈,重新连接节点。 代码示例如下: ```python class Solution(object): def reorderList(self, head): if not head: return stack = [] s = head while s.next: stack.append(s.next) s = s.next s = head n = 0 while stack: if n % 2 == 0: one = stack.pop() else: one = stack.pop(0) one.next = None s.next = one s = s.next n += 1 ``` 这段代码中,首先判断头节点是否为空,然后初始化一个栈,并将链表中的其它节点压入栈中。然后,重新遍历链表,根据指定的规则从栈中出栈,并重新连接节点。 这样就能实现重排链表的功能。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [LeetCode: 重排链表 python实现](https://blog.csdn.net/weixin_43786241/article/details/105752892)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] - *2* *3* [L2-022 重排链表(Python3)](https://blog.csdn.net/weixin_55730361/article/details/126516893)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值