反转一个单链表。
示例:
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
进阶:
你可以迭代或递归地反转链表。你能否用两种方法解决这道题?
第一思路 使用额外空间栈 来解决 后进先出
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
Stack<ListNode> list = new Stack<>();
public ListNode reverseList(ListNode head) {
ListNode p = head;
while (p != null) {
list.add(p);
p = p.next;
}
ListNode newHead = null;
if (list.size() > 0) {
newHead = list.pop();
} else {
return newHead;
}
ListNode q = newHead;
while (list.size() > 0) {
ListNode tmp = list.pop();
q.next = tmp;
q = q.next;
}
q.next = null;
return newHead;
}
}
时间复杂度O(n) 空间O(n)
2. 进阶 迭代 双指针 将后一个节点反转过来往回指
class Solution {
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)
3. 递归
每次将处理的head 反转过来
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) 空间复杂度,使用递归将会使用隐式栈空间,递归的深度会达到n层