反转链表
Reverse Linked List
解
方法一:迭代
/**
https://leetcode-cn.com/problems/reverse-linked-list/ * Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode* cur = NULL;
while (head) {
ListNode* temp = cur;
cur = head;
head = head->next;
cur->next = temp;
}
return cur;
}
};
方法二:递归
/**
https://leetcode-cn.com/problems/reverse-linked-list/ * Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if (head == NULL || head->next == NULL) {
return head;
}
ListNode* cur = reverseList(head->next);
head->next->next = head;
head->next = NULL;
return cur;
}
};
来源:CSDN
作者:三九_感冒灵
链接:https://blog.csdn.net/weixin_43443553/article/details/104617057