难度简单1422
反转一个单链表。
示例:
输入: 1->2->3->4->5->NULL 输出: 5->4->3->2->1->NULL
进阶:
你可以迭代或递归地反转链表。你能否用两种方法解决这道题?
反转链表, 需要多训练训练,思路就是把节点倒着指过来。
1、迭代法
/**
* 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 *pre = head;
ListNode *cur = NULL;
while(pre != NULL){
ListNode *tmp = pre->next;
pre->next = cur;
cur = pre;
pre = tmp;
}
return cur;
}
};
-----------------------2021年1月27日更新-----------------------
2、递归
今天针对反转这类题的递归方法有所收获,特此来更新一下
/**
* 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 == nullptr || head->next == nullptr){
return head;
}
ListNode* last = reverseList(head->next);
head->next->next = head;
head->next = nullptr;
return last;
}
};