题目
菜鸟解答
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* reverseList(struct ListNode* head){
struct ListNode *scan ,*prev,*next;
if (NULL == head || NULL == head->next) {
return head;
}
prev = head;
scan = head->next;
head->next = NULL;
while(scan != NULL) {
next = scan->next;
scan->next = prev;
prev = scan;
scan = next;
}
return prev;
}
评论区官方解答
原链接为https://leetcode-cn.com/problems/reverse-linked-list/solution/fan-zhuan-lian-biao-by-leetcode/
迭代法,即同上
复杂度分析 :
时间复杂度:O(n)O(n),假设 nn 是列表的长度,时间复杂度是 O(n)O(n)。
空间复杂度:O(1)O(1)
递归法
从复杂度上不是最优,但是思路 ORZ
自行想了半天写不出递归解法,看了官网代码还要理解一会…ORZ
假设 N1->N2->N3
N1 :第一层调用
p = R(N1->next)=R(N2)
-> p = N3
N1->next->next =N2->next =head = N1
N1->next = NULL
return p=N3
N2 : 第二层调用
p = R(N2->next)=R(N3) -> p = N3
N2->next->next =N3->next =head = N2
N2->next = NULL
return p=N3
N3 : 第三层调用
∵ N3->next == NULL ∴ return head = N3
/*递归的实现 在当前节点需要做什么翻转操作: 当前节点的下一个节点的next要重定向为当前节点 当前节点的下一个节点置null 由其上一层节点重新赋值*/
struct ListNode* reverseList(struct ListNode* head){
struct ListNode *last = NULL;
if (NULL == head || NULL == head->next) {
return head;
}
last = reverseList(head->next); /*最后一层的时候 last->next = null 所以return last 到倒数第二层*/
head->next->next = head;
head->next = NULL;
return last; /*一直返回last 变为首节点*/
}