题目
思路
- 思路一:使用栈
- 思路二:递归
-
代码
//1.使用栈public void reorderList(ListNode head) {if (head == null || head.next == null || head.next.next == null) return;LinkedList<ListNode> queue = new LinkedList<>();while (head != null) {queue.add(head);head = head.next;}ListNode dummy = new ListNode(0);while(!queue.isEmpty()) {dummy.next = queue.pollFirst();if (queue.isEmpty()) {dummy.next.next = null;return;}dummy.next.next = queue.pollLast();dummy = dummy.next.next;dummy.next = null;}}//2.递归ListNode dummy;public void reorderList(ListNode head) {if (head == null) return;dummy = head;recur(head.next);}public ListNode recur(ListNode tail) {if (tail == null || tail.next == null) return tail;ListNode nTail = recur(tail.next);if (nTail == null) return nTail;ListNode next = dummy.next;dummy.next = nTail;nTail.next = next;dummy = next;if ( tail == dummy || dummy.next == tail) {tail.next = null;return null;}return tail;}
