import java.util.*;
/*
* public class ListNode {
* int val;
* ListNode next = null;
* public ListNode(int val) {
* this.val = val;
* }
* }
*/
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param head ListNode类
* @return ListNode类
*/
public ListNode ReverseList (ListNode head) {
// write code here
Deque<ListNode> stackDeque=new ArrayDeque<>();
ListNode current=head;
while(current!=null) {
stackDeque.push(current);
current=current.next;
}
if(stackDeque.isEmpty()) {
return null;
}
ListNode newheadListNode=stackDeque.pop();
current=newheadListNode;
while(!stackDeque.isEmpty()) {
ListNode new_currListNode=stackDeque.pop();
current.next=new_currListNode;
current=current.next;
}
current.next=null;
return newheadListNode ;
}
}
反转链表推荐使用栈来做,先把链表中的所有结点压入栈中,这里一定要注意一个点,由于Deque本质是双端队列,如果我添加元素使用add而不是push,那就会默认按照队列来做,就不是我们想要的栈了,最后结果肯定也是错的。通过使用栈,来达到反转链表。如果是空链表,记得返回null



京公网安备 11010502036488号