题目
给你单链表的头节点 head ,请你反转链表,并返回反转后的链表头节点。
思路
1.可以直接遍历链表,双指针指向当前节点前一个和后一个节点,将两者先后顺序调换即可。
2.递归从后往前调整链表顺序。
代码
/**非递归方法
* 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){
return nullptr;
}
ListNode *pre = head->next,*last = head,*next = head->next;
last->next = nullptr;
while(pre){
next = pre->next;
pre->next = last;
last = pre;
pre = next;
}
return last;
}
};
/**递归方法
* 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 *pre = reverseList(head->next);
head->next->next = head;
head->next =nullptr;
return pre;
}
};