/*
public class ListNode {
    int val;
    ListNode next = null;

    ListNode(int val) {
        this.val = val;
    }
}*/
/*
这道题是反转列表,使用栈,时间空间复杂度是O(n)
使用栈比使用列表方便
*/
import java.util.Stack;
public class Solution {
    public static ListNode ReverseList(ListNode head) {
        if(head==null){
            return null;
        }
        Stack<ListNode> stack = new Stack<ListNode>();
        while(head!=null){
            stack.push(head);
            head = head.next;
        }
        ListNode node = stack.pop();
        // 遍历链表节点时,头结点应存储成两个变量,一个用于遍历,一个用于最终返回头结点
        ListNode first = node;
        while(!stack.isEmpty()){
            ListNode temp = stack.pop();
            node.next = temp;
            node = temp;
        }
        // 这里很关键要让最后一个节点的next等于空,否则会构成环
        node.next = null;
        return first;
    }
}