重排链表
给定一个单链表L: L0→L1→…→Ln-1→Ln,
重新排列后为:L0→Ln→L1→Ln-1→L2→Ln-2→…
必须在不改变节点值的情况下进行原地操作。
您在真实的面试中是否遇到过这个题?
Yes
样例
给出链表 1->2->3->4->null
,重新排列后为1->4->2->3->null
。
- 常见的链表操作,先找到中间节点,然后逆转中间的后面节点,再前后节点合并
/** * Definition for ListNode. * public class ListNode { * int val; * ListNode next; * ListNode(int val) { * this.val = val; * this.next = null; * } * } */ public class Solution { /** * @param head: * The head of linked list. * @return: void */ public void reorderList(ListNode head) { // write your code here if (head == null || head.next == null) { return; } ListNode middle = findMiddenNode(head); ListNode node2 = reverseNode(middle.next); middle.next = null; mergeNode(head, node2); } public static ListNode findMiddenNode(ListNode head) { ListNode slow = head; ListNode fast = head.next; while (fast != null && fast.next != null) { slow = slow.next; fast = fast.next.next; } return slow; } public static ListNode reverseNode(ListNode head) { ListNode newHead = null; while (head != null) { ListNode tmp = head.next; head.next = newHead; newHead = head; head = tmp; } return newHead; } private void mergeNode(ListNode head1, ListNode head2) { int index = 0; ListNode resultHead = new ListNode(-1); while (head1 != null && head2 != null) { if (index % 2 == 0) { resultHead.next = head1; head1 = head1.next; } else { resultHead.next = head2; head2 = head2.next; } resultHead = resultHead.next; index++; } if (head1 != null) { resultHead.next = head1; } if (head2 != null) { resultHead.next = head2; } } }