反转链表
反转链表
http://www.nowcoder.com/questionTerminal/75e878df47f24fdc9dc3e400ec6058ca
栈的解法:先进后出
import java.util.*;
public class Solution {
public ListNode ReverseList(ListNode head) {
if (head == null) {
return null;
}
Stack<ListNode> stack = new Stack<>();
while (head != null) {
stack.push(head);
head = head.next;
}
// 生成新的反转链表
ListNode resultNode = stack.pop();
ListNode tempNode = resultNode;
while (!stack.isEmpty()) {
tempNode.next = stack.pop();
tempNode = tempNode.next;
}
// 将反转链表的最后置为null
tempNode.next = null;
return resultNode;
}
}
查看13道真题和解析