题目是给你单链表的头节点 head ,请你反转链表,并返回反转后的链表。请使用栈的java语言编写代码
时间: 2023-03-13 22:30:35 浏览: 107
算法-单链表遍历及反转(java)(csdn)————程序.pdf
public ListNode reverseListByStack(ListNode head) {
Stack<ListNode> stack = new Stack<>();
ListNode cur = head;
while (cur != null) {
stack.push(cur);
cur = cur.next;
}
ListNode newHead = stack.pop();
cur = newHead;
while (!stack.isEmpty()) {
cur.next = stack.pop();
cur = cur.next;
}
cur.next = null;
return newHead;
}
阅读全文