赞
踩
目录
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,再遍历一遍链表,重新赋值。
- /**
- * 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反过来指向它前面的结点
- 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;
- }
递归
- 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;
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。