- 使用栈是非常好的一个方法
- import java.util.*;包含了很多工具
import java.util.*;
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}*/
public class Solution {
public ListNode ReverseList(ListNode head) {
Stack<ListNode> stack = new Stack<>();
//把链表结点都放到栈里
while (head != null){
stack.push(head);
head = head.next;
}
if(stack.isEmpty())
return null;
ListNode node = stack.pop();
ListNode dummy = node;
while(!stack.isEmpty()){
ListNode tempNode = stack.pop();
node.next = tempNode;
node = node.next;
}
node.next = null;
return dummy;
}
}