#
反转链表
http://www.nowcoder.com/questionTerminal/75e878df47f24fdc9dc3e400ec6058ca
参考其他人的回答,总结了两种方法
- 使用JDK自带的栈,循环链表,将元素全部压入栈中。取出的时候因为栈FILO的特性,自然就反转了。这里需要注意将最后一个元素的next变为空,否则会出现死循环
- 使用辅助指针,指向新链表的头,以及旧链表的next
/**
* 第一种方式:使用栈
*/
public ListNode ReverseList(ListNode head) {
if (head == null || head.next == null) {
return head;
}
// 放入栈中
Stack<ListNode> stack = new Stack<>();
while (head != null) {
stack.push(head);
head = head.next;
}
ListNode newHead = stack.pop();
ListNode cur = newHead;
while (!stack.isEmpty()) {
cur.next = stack.pop();
cur = cur.next;
}
cur.next = null;
return newHead;
}
/**
* 第二种方式:使用辅助指针
*/
public ListNode ReverseList(ListNode head) {
if (head == null || head.next == null) {
return head;
}
// 用指针记录
ListNode newHead = null;
ListNode next;
while (head != null) {
// 指向下一个node
next = head.next;
// 将当前节点脱离远链表,作为新链表的头
head.next = newHead;
// 将newHead转为当前节点
newHead = head;
// head等于下一个节点
head = next;
}
return newHead;
}

查看3道真题和解析