给你单链表的头节点 head ,请你反转链表,并返回反转后的链表。
时间: 2024-03-19 10:39:25 浏览: 24
要反转一个单链表,可以使用迭代或递归的方法。
1. 迭代方法:
- 初始化三个指针:prev、curr 和 next,分别指向前一个节点、当前节点和下一个节点。
- 遍历链表,每次将当前节点的 next 指针指向前一个节点、 和 next 指针。
- 当遍历整个链表后,将链表的头节点指向 prev,即为反转后的链表。
以下是迭代方法的示例代码:
```python
def reverseList(head): prev = None
curr = head
while curr:
next = curr.next
curr.next = prev
prev = curr
curr = next
return prev
```
2. 递归方法:
- 递归地反转链表的子链表。
- 将当前节点的下一个节点的 next 指针指向当前节点,然后将当前节点的 next 指针置空。
- 返回反转后的链表的头节点。
以下是递归方法的示例代码:
```python
def reverseList(head):
if not head or not head.next:
return head
new_head = reverseList(head.next)
head.next.next = head
head.next = None
return new_head
```
相关问题
C语给你单链表的头节点 head ,请你反转链表,并返回反转后的链表。
好的,这是一道数据结构问题,我可以给你提供解答。以下是 C++ 代码实现:
```c++
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode* pre = nullptr;
ListNode* cur = head;
while (cur) {
ListNode* next = cur->next;
cur->next = pre;
pre = cur;
cur = next;
}
return pre;
}
};
```
这个方法会将原链表的每个节点指向其前一个节点,来实现整个链表的翻转。希望可以帮到你!
题目是给你单链表的头节点 head ,请你反转链表,并返回反转后的链表。请使用栈的java语言编写代码
public ListNode reverseListByStack(ListNode head) {
Stack<ListNode> stack = new Stack<>();
ListNode cur = head;
while (cur != null) {
stack.push(cur);
cur = cur.next;
}
ListNode newHead = stack.pop();
cur = newHead;
while (!stack.isEmpty()) {
cur.next = stack.pop();
cur = cur.next;
}
cur.next = null;
return newHead;
}