206. 反转链表
1、栈版本
public ListNode reverseList(ListNode head) {
Stack<ListNode> s = new Stack<>();
ListNode t = head;
while (t != null) {
s.push(t);
t = t.next;
}
//先取出一个
ListNode newHead = new ListNode(-1);
t = newHead;
while (!s.empty()) {
//去出元素
ListNode t1 = s.pop();
t.next = t1;
t1.next = null;
t = t.next;
}
return newHead.next;
}
2、快慢指针版本
public ListNode reverseList(ListNode head) {
ListNode pre = null;
ListNode cur = head;
while (cur != null) {
ListNode t = cur;
cur = cur.next;
t.next = pre;
pre = t;
}
return pre;
}