6-2 reverse linked list
时间: 2023-04-27 07:00:34 浏览: 199
6-2 反转链表
反转一个单链表。
示例:
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
进阶:
你可以迭代或递归地反转链表。你能否用两种方法解决这道题?
相关问题
6-2 Reverse Linked List 6-2 反向链表
### 如何反转链表
在编程中,反转单向链表是一个常见的操作。下面将介绍一种迭代方法来实现这一功能。
#### 迭代法反转链表
通过创建三个指针变量 `prev`、`current` 和 `next` 来逐步遍历并翻转节点之间的指向关系[^1]:
```python
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def reverse_linked_list(head: ListNode) -> ListNode:
prev = None
current = head
while current is not None:
next_node = current.next # Store reference to next node before changing it.
current.next = prev # Reverse link direction.
prev = current # Move previous pointer forward one step.
current = next_node # Move current pointer forward one step.
return prev # New head of reversed list will be last non-null 'prev'.
```
此算法的时间复杂度为 O(n),其中 n 是列表中的元素数量;空间复杂度为 O(1),因为它只使用固定额外内存完成任务。
为了更好地理解上述过程的工作原理,考虑如下图所示的一个简单例子,在每一步之后展示了各个指针的状态变化情况。
初始状态:
```
NULL <- A -> B -> C -> D -> NULL
prev curr next
```
第一次循环结束后的状态:
```
NULL <- A <-> B -> C -> D -> NULL
prev curr next
```
第二次循环结束后:
```
NULL <- A <- B <-> C -> D -> NULL
prev curr next
```
最终结果将是所有箭头方向都被逆转过来,形成一个新的从D到A的链接序列。
7-2 Mergin7-2 Merging Linked Lists 分数 15 作者 陈越 单位 浙江大学 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. Sample Input: 00100 01000 7 02233 2 34891 00100 6 00001 34891 3 10086 01000 1 02233 00033 5 -1 10086 4 00033 00001 7 -1 Sample Output: 01000 1 02233 02233 2 00001 00001 7 34891 34891 3 10086 10086 4 00100 00100 6 00033 00033 5 -1 代码长度限制 16 KB 时间限制 400 ms 内存限制 64 MB 栈限制g Linked Lists c语言
### 解决方案
为了实现两个单链表的合并操作,其中短链表需要先反转再插入到长链表中,可以按照如下方法完成:
定义函数 `mergeAndReverse` 来处理这个问题。该函数接收两个链表头指针作为参数,并返回新的合并后的链表头部。
#### 反转链表
首先编写用于反转链表的方法 `reverseList`:
```c
struct ListNode* reverseList(struct ListNode *head) {
struct ListNode *prev = NULL;
struct ListNode *current = head;
while (current != NULL) {
struct ListNode *nextTemp = current->next; // 记录下一个节点
current->next = prev; // 当前节点指向前面
prev = current; // 前面移动至当前
current = nextTemp; // 移动到下一位
}
return prev;
}
```
#### 合并链表
接着创建一个新的辅助函数来执行实际的合并逻辑:
```c
struct ListNode* mergeTwoLists(struct ListNode* l1, struct ListNode* l2){
if (!l1 || !l2) return l1 ? l1 : l2;
struct ListNode dummyNode;
struct ListNode *tail = &dummyNode;
tail->next = l1;
// 将第二个链表反转
l2 = reverseList(l2);
// 找到第一个链表最后一个元素
while(tail && tail->next){
tail = tail->next;
}
// 连接两部分
tail->next = l2;
return dummyNode.next;
}
```
上述代码实现了将较短链表反转后连接到较长链表的操作[^1]。这里假设输入的两个链表分别为 `l1` 和 `l2`,并且已经确定了哪个更长。如果不确定长度,则可以在调用此函数之前计算两者长度或者采用其他策略决定如何拼接[^2]。
#### 完整流程概述
整个过程涉及三个主要步骤:
- 判断哪条链表更长;
- 对较短的一方做反转处理;
- 把经过反转的小链表追加到大链表末端。
这种方法不仅解决了原始需求——即把一条链表反向加入另一条之中;同时也保持了原有节点间的相对位置不变,从而确保最终得到的结果符合预期[^3]。
阅读全文
相关推荐















