题目
反转一个单链表。 「示例:」
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
进阶: 你可以迭代或递归地反转链表。你能否用两种方法解决这道题?
❝来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/reverse-linked-list
❞
题解
「迭代」借助三个指针,顺序反转; 「递归」则相反, 反转的顺序是由后往前进行,采用递归调用的方式,遍历至尾部节点,依次反转直到递归回到第一个节点停止,返回反转后的链表头指针。
代码
「迭代法」
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
public ListNode reverseList(ListNode head) {
ListNode prev = null;
ListNode curr = head;
while (curr != null) {
ListNode nextTemp = curr.next;
curr.next = prev;
prev = curr;
curr = nextTemp;
}
return prev;
}
时间复杂度: O(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 || head->next == NULL){
return head;
}
ListNode *p = reverseList(head->next);
head->next->next = head;
head->next = NULL;
return p;
}
};
时间复杂度: O(n) 空间复杂度: O(n)