package top.ssyuan.easy;import java.util.ArrayList;import java.util.Stack;import top.ssyuan.Util;/** * 206. Reverse Linked List * Easy * <p> * 7972 * <p> * 147 * <p> * Add to List * <p> * Share * Given the head of a singly linked list, reverse the list, and return the reversed list. * <p> * <p> * <p> * Example 1: * <p> * <p> * Input: head = [1,2,3,4,5] * Output: [5,4,3,2,1] * Example 2: * <p> * <p> * Input: head = [1,2] * Output: [2,1] * Example 3: * <p> * Input: head = [] * Output: [] */public class Lesson206 { public static void main(String[] args) { Lesson206 lesson = new Lesson206(); ListNode head = lesson.genLinkList(10); lesson.printLink(head); //head = new Solution1().reverseList(head); head = new Solution2().reverseList(head); Util.println(""); lesson.printLink(head); } private void printLink(ListNode head) { ListNode node = head; while (node != null) { Util.print(node.val + "->"); node = node.next; } } private ListNode genLinkList(int count) { if (count < 1) return null; ListNode head = new ListNode((int) (Math.random() * 100)); ListNode curNode = head; for (int i = 1; i < count; i++) { curNode.next = new ListNode((int) (Math.random() * 100)); curNode = curNode.next; } return head; } //Definition for singly-linked list. public class ListNode { int val; ListNode next; ListNode() { } ListNode(int val) { this.val = val; } ListNode(int val, ListNode next) { this.val = val; this.next = next; } } static class Solution1 { public ListNode reverseList(ListNode head) { if (head == null) { return null; } Stack<ListNode> nodes = new Stack<>(); ListNode node = head; ListNode tmp; while (node != null) { nodes.push(node); tmp = node; node = node.next; tmp.next = null; } head = nodes.pop(); node = head; while (node != null && !nodes.isEmpty()) { node.next = nodes.pop(); node = node.next; } return head; } } static class Solution2 { public ListNode reverseList(ListNode head) { if (head == null) { return null; } ListNode node = head; ListNode pre = null; ListNode tmp = node; while (node != null) { tmp = node; node = node.next; tmp.next = pre; pre = tmp; } return tmp; } }}