此题是链表中比较基础的题目,需要彻底掌握,这里提供四种方法:
递归法:
/**
* 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* res = reverseList(head->next);
head->next->next = head;
head->next = nullptr;
return res;
}
};
双指针:
/**
* 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=nullptr, *pre=head;
while(pre!=nullptr){
ListNode *temp = pre->next;
pre->next = cur;
cur = pre;
pre = temp;
}
return cur;
}
};
栈方法:
/**
* 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)
return nullptr;
stack<ListNode*> data;
while(head!=nullptr){
data.push(head);
head=head->next;
}
ListNode* cur = data.top(), *out;
out = cur;
data.pop();
while(!data.empty()){
ListNode* temp = data.top();
data.pop();
cur->next = temp;
cur = temp;
}
cur->next=nullptr;
return out;
}
};
头插法:
/**
* 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* new_start = new ListNode(0), *out;
while(head!=nullptr){
ListNode* cur = head->next;
head->next = new_start->next;
new_start->next = head;
head = cur;
}
out = new_start->next;
delete new_start;
return out;
}
};