1.题目
2.解法1(使用栈,还要破除原来的关系)
import java.util.Stack;
public class Solution {
public ListNode ReverseList(ListNode head) {
if (head == null || head.next == null) return head;
Stack<ListNode> stk = new Stack<>();
while (head != null) {
stk.push(head);
head = head.next;
}
// 不创建虚假结点
if (!stk.isEmpty()) head = stk.pop();
ListNode cur = head;
ListNode tmp = null;
while (!stk.isEmpty()) {
tmp = stk.pop();
tmp.next = null;
cur.next = tmp;
cur = tmp;
}
return head;
}
}
import java.util.Stack;
public class Solution {
public ListNode ReverseList(ListNode head) {
if (head == null || head.next == null) return head;
Stack<ListNode> stk = new Stack<>();
while (head != null) {
stk.push(head);
head = head.next;
}
// 假设我有一个虚假的头结点
ListNode first = new ListNode(0);
ListNode tmp = first;
while (!stk.isEmpty()) {
// 将本结点及next安排好后,再换结点
head = stk.pop();
head.next = null;
tmp.next = head;
tmp = head;
}
return first.next;
}
== 时间复杂度为O(n), 空间复杂度为O(n)==
解法2:使用3个结点(最佳解法)
import java.util.Stack;
public class Solution {
public ListNode ReverseList(ListNode head) {
if (head == null || head.next == null) return head;
ListNode pre = null;
ListNode next = null;
// 三个结点的移动
while (head != null) {
next = head.next;
head.next = pre;
pre = head;
head = next;
}
return pre;
}
}
时间复杂度为O(n), 空间复杂度为O(1)