反转一个单链表。
示例:
输入: 1->2->3->4->5
输出: 5->4->3->2->1
进阶:
你可以迭代或递归地反转链表。你能否用两种方法解决这道题?
public class ReverseList {
@Test
public void reverseListTest() {
ListNode head = new ListNode(1);
head.next = new ListNode(2);
head.next.next = new ListNode(3);
head.next.next.next = new ListNode(4);
head.next.next.next.next = new ListNode(5);
reverseList(head);
}
public ListNode reverseList(ListNode head) {
if (head == null) return null;
Stack<ListNode> stack = new Stack<>();
while (head != null) {
stack.push(head);
head = head.next;
}
ListNode node = stack.pop();
ListNode temp = node;
while (stack.size() > 0) {
ListNode preNode = stack.pop();
node.next = preNode;
node = preNode;
}
node.next = null;
return temp;
}
}