方法1:利用栈
public ListNode ReverseList(ListNode head) {
if (head == null) {
return null;
}
ListNode tmp = head;
Stack<ListNode> stack = new Stack<>();
while (tmp.next != null) {
stack.push(tmp);
tmp = tmp.next;
stack.peek().next = null;
}
head = tmp;
while (!stack.isEmpty()) {
tmp.next = stack.pop();
tmp = tmp.next;
}
return head;
}
方法2:一个节点一个节点的反转
public static ListNode ReverseList(ListNode head) {
if (head == null)
return null;
ListNode pre = null;
ListNode next = null;
while (head != null) {
next = head.next;
head.next = pre;
pre = head;
head = next;
}
return pre;
}