目录
题目链接
https://leetcode-cn.com/problems/UHnkqh/
题目
给定单链表的头节点
head
,请反转链表,并返回反转后的链表的头节点。
示例
示例 1:
输入:head = [1,2,3,4,5]
输出:[5,4,3,2,1]示例 2:
输入:head = [1,2]
输出:[2,1]示例 3:
输入:head = []
输出:[]
提示
- 链表中节点的数目范围是
[0, 5000]
-5000 <= Node.val <= 5000
思路一
遍历链表,用一个栈储存每个结点的val,再遍历一遍链表,重新赋值。
C++ Code
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* reverseList(ListNode* head) {
stack <int> L;
ListNode* cur=head;
while(cur!=NULL)
{
L.push(cur->val);
cur=cur->next;
}
cur=head;
while(cur!=NULL)
{
cur->val=L.top();
L.pop();
cur=cur->next;
}
return head;
}
};
思路二
将每个结点的next反过来指向它前面的结点
C++ Code
public:
ListNode* reverseList1(ListNode* head) {
ListNode* prev = nullptr;
ListNode* curr = head;
while (curr)
{
ListNode* next = curr->next;
curr->next = prev;
prev = curr;
curr = next;
}
return prev;
}
思路三
递归
C++ Code
public ListNode reverseList(ListNode head) {
// 1. 递归终止条件
if (head == null || head.next == null) {
return head;
}
ListNode p = reverseList(head.next);
head.next.next = head;
head.next = null;
return p;
}