1.使用栈结构--因为栈是先进后出的,所以可以将链表的每个结点入栈,然后头节点设置为栈的栈顶元素,然后在以此出栈
/**
* 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==NULL||head->next==NULL){
return head;
}
stack<ListNode*>stk;
while(head!=NULL){
stk.push(head);
head=head->next;
}
head=stk.top();
stk.pop();
ListNode *result=head;
while(!stk.empty()){
head->next=stk.top();
stk.pop();
head=head->next;
}
head->next=NULL;//因为链表最后结点一定是NULL;
return result;
}
};
2.双链表求解
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode *rear=NULL;
while(head!=NULL){
ListNode *front=head->next;
head->next=rear;
rear=head;
head=front;
}
return rear;
}
};
3.递归解决
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if(head==NULL||head->next==NULL){
return head;
}
ListNode *result=reverseList(head->next);//result就是最终的头节点
head->next->next=head;
head->next=NULL;
return result;
}
};
以上递归方法 回溯(出栈)时较慢,因为我们是在函数回溯时才进行的修改指针方向.尾递归正好解决这种问题.
4.尾递归
class Solution {
public:
ListNode *func(ListNode *head,ListNode *newhead){
if(head==NULL){
return newhead;
}
ListNode *next=head->next;
head->next=newhead;
return func(next,head);
}
ListNode* reverseList(ListNode* head) {
return func(head,NULL);
}
};
这种方法就是每次递归时就直接更改了指针的方向,而并非是回溯时才更改,而出栈的效率要比上一个递归要好.