1、反转链表
https://leetcode-cn.com/explore/learn/card/linked-list/195/classic-problems/750/
在该算法中,每个结点只移动一次。
因此,时间复杂度为 O(N),其中 N 是链表的长度。我们只使用常量级的额外空间,所以空间复杂度为 O(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) {
if(head==NULL) return head;
ListNode* h=head;
while(h->next)
{
ListNode* str=h->next;
h->next=h->next->next;
str->next=head;
head=str;
}
return head;
}
};
二、递归方法:
//递归方法
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if(head==NULL||head->next==NULL) return head;
else
{
ListNode* cur=reverseList(head->next);
head->next->next=head;
head->next=NULL;
return cur;
}
}
};