题目描述:输入一个链表,反转链表后,输出新链表的表头。
题解:
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}*/
import java.util.Stack;
public class Solution {
public ListNode ReverseList(ListNode head) {
if(head==null)
return null;
Stack<ListNode> stack = new Stack<>();
while(head.next!=null){
ListNode next = head.next;
head.next = stack.isEmpty() ? null : stack.peek();
stack.push(head);
head = next;
}
head.next = stack.isEmpty() ? null : stack.peek();
return head;
}
/* 头插法
public ListNode ReverseList(ListNode head) {
ListNode node = new ListNode(-1);
while(head!=null){
ListNode newHead = head.next;
ListNode next = node.next;
node.next = head;
head.next = next;
head = newHead;
}
return node.next;
}
*/
}