题目
反转一个单链表。
示例:
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
如果是
思路一 迭代
遍历链表时,将每一个结点指向上一个结点,还需要一个变量来记住下一个结点
class Solution {
public ListNode reverseList(ListNode head) {
ListNode pre = null;
ListNode cur = head;
ListNode temp = null;
while (cur != null) {
temp = cur.next; //记录下一个结点
cur.next = pre; //当前结点反转指向上一个结点
pre = cur; //在下一个结点操作时,用来指向上一个结点
cur = temp; //到下一个结点继续进行操作
}
return pre;
}
}
复杂度分析
时间复杂度:O(n),n 是列表的长度
空间复杂度:O(1)。
思路二 使用递归
和思路一差不多
class Solution {
ListNode pre = null, tmp = null;
public ListNode reverseList(ListNode head) {
if (head == null) //递归停止条件
return pre;
tmp = head.next;
head.next = pre;
pre = head;
head = tmp;
return reverseList(head);
}
}
复杂度分析
时间复杂度:O(n),n 是列表的长度
空间复杂度:O(n),由于使用递归,将会使用隐式栈空间。递归深度可能会达到 n层。
思路三 递归
另外思路的递归
class Solution {
public ListNode reverseList(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode cur = reverseList(head.next); //一直到链表的尾,cur一直指向链表的尾部
head.next.next = head; //从尾部开始,结点指向前面节点 比如1-2-3-4-5,从4开始,4.next.next = 5.next = 4,然后4.next = null,断掉
head.next = null; //本身的指向断掉
return cur;
}
}
时间复杂度:O(n)
空间复杂度:O(n)