3.反转链表
题目描述
给定单链表的头节点head,请你反转链表,并返回反转后的链表.
原题链接
https://leetcode-cn.com/problems/reverse-linked-list/description/
样例
输入:head = [1,2,3,4,5]
输出:[5,4,3,2,1]
输入:head = [1,2]
输出:[2,1]
输入:head = []
输出:[]
算法
(链表操作,迭代) O(n)
方法一:
迭代
方法二:
递归
每次递归会先把后n−1个节点翻转,然后把当前的头结点接在后n−1个节点的后面。
代码
/**
* 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) {
// 方法一:
// if (head == nullptr || head->next == nullptr) {
// return head;
// }
// ListNode* a = head;
// ListNode* b = a->next;
// while (b) {
// ListNode* c = b->next;
// b->next = a;
// a = b;
// b = c;
// }
// head->next = nullptr;
// return a;
// 方法二
// if (!head || !head->next) {
// return head;
// }
// ListNode* tail = reverseList(head->next);
// head->next->next = head;
// head->next = nullptr;
// return tail;
}
};
本文来自博客园,作者:jsqup,转载请注明原文链接:https://www.cnblogs.com/jsqup/p/15690119.html