题目
给定一个单链表 L:L0→L1→…→Ln-1→Ln ,
将其重新排列后变为: L0→Ln→L1→Ln-1→L2→Ln-2→…
你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。
示例 1:
给定链表 1->2->3->4, 重新排列为 1->4->2->3.
示例 2:
给定链表 1->2->3->4->5, 重新排列为 1->5->2->4->3.
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/reorder-list
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
答案
/**
* 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; }
* }
*/
class Solution {
public void reorderList(ListNode head) {
ListNode slow = head;
ListNode fast = head;
ListNode result = new ListNode();
ListNode result1 = result;
while (fast.next != null && fast.next.next != null) {
slow = slow.next;
fast = fast.next.next;
}
ListNode secondHead = slow.next;
slow.next = null;
secondHead = revert(secondHead);
while (secondHead != null || head != null) {
result.next = head;
head = head.next;
if (secondHead != null) {
result.next.next = secondHead;
secondHead = secondHead.next;
}
result = result.next.next;
}
head = result1.next;
}
public ListNode revert(ListNode head) {
ListNode result = head;
while (head != null && head.next != null) {
result = revert(head.next);
head.next.next = head;
head.next = null;
}
return result;
}
}