//链表逆序 public ListNode reverse(ListNode listNode){ if (listNode == null) { returnnull; } ListNode pre = null; ListNode cur = listNode; ListNode next = cur.next;
while (next != null) { cur.next = pre; pre = cur; cur = next; next = cur.next; } cur.next = pre; return cur; }
pre cur next null [] -> [] -> [] -> [] -> null
cur.next = pre;pre = cur;next=cur.next; pre cur next null <- [] x [] -> [] -> [] -> null
cur.next = pre;pre = cur;next=cur.next; pre cur next null <- [] <- [] x [] -> [] -> null
cur.next = pre;pre = cur;next=cur.next; pre cur next null <- [] <- [] <- [] x [] -> null
cur.next = pre; cur null <- [] <- [] <- [] <- [] x null
//链表逆序(使用栈做辅助) public ListNode reverseList(ListNode head){ Stack<ListNode> stack = new Stack<>(); while (head != null) { stack.push(head); head = head.next; } while (!stack.isEmpty()) { head = stack.pop(); } return head; }
//从尾到头打印节点(使用栈做辅助) public ArrayList<Integer> reList(ListNode head){ ArrayList<Integer> arrayList = new ArrayList<>(); Stack<Integer> stack = new Stack<>(); while (head != null) { stack.push(head.val); } while (!stack.isEmpty()) { arrayList.add(stack.pop()); } return arrayList; }