L2-022 重排链表 (25 分)天梯

本文详细解析了一种重排链表的算法实现,通过读入、排序和模拟三个步骤,将给定的单链表重新排列为交错的顺序。输入包含链表的初始状态,输出则展示了重排后的链表结构,适用于链表长度至少为2的情况。

L2-022 重排链表 (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

 

 

题解:

读入->排序->模拟

需要注意的是数据比较坑(第4个点),可能存在不再一个链表上的两个结点,所有需要记录一下链表长度。

 

#include <iostream>
#include <map>
using namespace std;
struct node
{
	string address;
	int data;
	string next;
}a[100010],s,tmp;
map<string,node> mp;
int main()
{
	cin>>s.address>>s.data;
	for(int i=0;i<s.data;i++)
	{
		cin>>tmp.address>>tmp.data>>tmp.next;
		mp[tmp.address]=tmp;
	}
	int len=0;
	for(int i=0;i<s.data;i++)
	{
		len++;
		a[i]=mp[s.address];
		s.address=a[i].next;
		if(s.address=="-1")break;
	}
	int count=1;
	for(int i=0;i<(len+1)/2;i++)
	{
		if(count%2==1)
		{
			
			cout<<a[len-i-1].address<<" "<<a[len-i-1].data<<" ";
			if(count!=len)
			{
				cout<<a[i].address<<endl;
			}
			else
			{
				cout<<-1<<endl;
				break;
			}
			count++;
		}
		if(count%2==0)
		{
			
			cout<<a[i].address<<" "<<a[i].data<<" ";
			if(count!=len)
			{
				cout<<a[len-i-2].address<<endl;
			}
			else
			{
				cout<<-1<<endl;
				break;
			}
			count++;
		}
	}
	return 0;
}

 

### 关于天梯赛 L2-022 重排链表的解法 #### 题目析 题目要求将一个单向链表 \(L\) 的节点按照特定顺序重新排列。具体来说,原链表的形式为 \(L_0 \rightarrow L_1 \rightarrow ... \rightarrow L_{n-1} \rightarrow L_n\),目标是将其转换成 \(L_0 \rightarrow L_n \rightarrow L_1 \rightarrow L_{n-1} \rightarrow L_2 \rightarrow L_{n-2} \rightarrow ...\)[^3]。 为了完成这一任务,可以解为以下几个部的操作: 1. **找到链表的中间节点**:通过快慢指针的方法来定位链表的中点位置[^2]。 2. **翻转后半部链表**:将链表从中点断开,并反转后半部链表。 3. **合并前后两部链表**:交替连接前半部和已翻转后的后半部链表。 以下是基于上述逻辑的具体实现代码。 --- ### C++ 实现 ```cpp #include <iostream> using namespace std; struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(nullptr) {} }; // 找到链表的中点 ListNode* findMiddle(ListNode* head) { ListNode* slow = head; ListNode* fast = head; while (fast->next && fast->next->next) { slow = slow->next; fast = fast->next->next; } return slow; } // 翻转链表 ListNode* reverseList(ListNode* head) { ListNode* prev = nullptr; ListNode* curr = head; while (curr) { ListNode* temp = curr->next; curr->next = prev; prev = curr; curr = temp; } return prev; } // 合并两个链表 void mergeLists(ListNode* l1, ListNode* l2) { while (l1 && l2) { ListNode* tmp1 = l1->next; ListNode* tmp2 = l2->next; l1->next = l2; if (!tmp1) break; // 如果前面已经为空,则结束 l2->next = tmp1; l1 = tmp1; l2 = tmp2; } } // 主函数用于执行整个过程 void reorderList(ListNode* head) { if (!head || !head->next) return; // Step 1: 找到中点 ListNode* mid = findMiddle(head); // Step 2: 断开链表并将后半部翻转 ListNode* secondHalfStart = reverseList(mid->next); mid->next = nullptr; // Step 3: 合并两个链表 mergeLists(head, secondHalfStart); } ``` --- ### Python 实现 ```python class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next def find_middle(head): slow, fast = head, head while fast and fast.next and fast.next.next: slow = slow.next fast = fast.next.next return slow def reverse_list(head): prev, curr = None, head while curr: nxt = curr.next curr.next = prev prev = curr curr = nxt return prev def merge_lists(l1, l2): while l1 and l2: l1_tmp, l2_tmp = l1.next, l2.next l1.next = l2 if not l1_tmp: break l2.next = l1_tmp l1 = l1_tmp l2 = l2_tmp def reorder_list(head): if not head or not head.next: return # Step 1: Find the middle of the list mid = find_middle(head) # Step 2: Reverse the second half of the list second_half_start = reverse_list(mid.next) mid.next = None # Step 3: Merge two lists together merge_lists(head, second_half_start) # Helper function to print linked list def print_linked_list(head): current = head result = [] while current: result.append(str(current.val)) current = current.next print(" -> ".join(result)) # Example usage if __name__ == "__main__": nodes = [i for i in range(1, 6)] dummy_head = ListNode(-1) current = dummy_head for node_val in nodes: current.next = ListNode(node_val) current = current.next print("Original List:") print_linked_list(dummy_head.next) reorder_list(dummy_head.next) print("Reordered List:") print_linked_list(dummy_head.next) ``` --- ### 方法解析 1. **寻找中点** 使用快慢指针技术,`slow` 和 `fast` 初始都指向头结点。每次迭代时,`slow` 移动一步而 `fast` 移动两步。当 `fast` 达到链表末尾时,`slow` 即位于链表中点的位置。 2. **翻转链表** 对链表中的每一个节点,改变其 `next` 指针的方向,从而达到翻转的效果。 3. **合并链表** 将原始链表为两部后,依次从这两部取节点进行拼接,最终形成新的链表结构。 --- ### 时间复杂度与空间复杂度 - **时间复杂度**: 整体算法的时间复杂度为 \(O(n)\),其中 \(n\)链表长度。这包括了三个主要阶段:寻找中点 (\(O(n/2)\))、翻转链表 (\(O(n/2)\)) 和合并链表 (\(O(n)\))- **空间复杂度**: 空间复杂度为 \(O(1)\),因为只用了常数级别的额外存储空间。 ---
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值