public static void main(String[] args) {
ListNode head = new ListNode();
head.next = new ListNode();
head.data = 1;
head.next.data = 2;
head.next.next = new ListNode();
head.next.next.data = 3;
Stack<ListNode> stack = revser(head);
for (int i = 0; i < stack.size(); i++) {
System.out.println(stack.pop());
}
}
public static Stack<ListNode> revser(ListNode head) {
Stack<ListNode> stack = new Stack<ListNode>();
if (head == null) {
return null;
}
while (head.next != null) {
stack.push(head);
head = head.next;
}
ListNode newhead = stack.pop();// 指针newhead
ListNode resulthead = newhead;
while (stack != null) {
newhead.next = stack.pop();
newhead = newhead.next;
}
return stack;
}
ListNode head = new ListNode();
head.next = new ListNode();
head.data = 1;
head.next.data = 2;
head.next.next = new ListNode();
head.next.next.data = 3;
Stack<ListNode> stack = revser(head);
for (int i = 0; i < stack.size(); i++) {
System.out.println(stack.pop());
}
}
public static Stack<ListNode> revser(ListNode head) {
Stack<ListNode> stack = new Stack<ListNode>();
if (head == null) {
return null;
}
while (head.next != null) {
stack.push(head);
head = head.next;
}
ListNode newhead = stack.pop();// 指针newhead
ListNode resulthead = newhead;
while (stack != null) {
newhead.next = stack.pop();
newhead = newhead.next;
}
return stack;
}