Leetcode: Reorder List

Given a singly linked list L: L0L1→…→Ln-1Ln,
reorder it to: L0LnL1Ln-1L2Ln-2→…

You must do this in-place without altering the nodes' values.

For example,
Given {1,2,3,4}, reorder it to {1,4,2,3}.

/**
 * Definition for singly-linked list.
 * class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
	public void reorderList(ListNode head) {
		// IMPORTANT: Please reset any member data you declared, as
		// the same Solution instance will be reused for each test case.
		if (head == null)
			return;
		ListNode slow = head;
		ListNode fast = head;
		while (fast != null && fast.next != null) {
			slow = slow.next;
			fast = fast.next.next;
		}
		ListNode temp = slow.next;
		slow.next = null;
		slow = temp;
		ListNode head2 = new ListNode(0);
		while (slow != null) {
			temp = slow;
			slow = slow.next;
			temp.next = head2.next;
			head2.next = temp;
		}
		ListNode pointer1 = head;
		ListNode pointer2 = head2.next;
		while (pointer1 != null && pointer2 != null) {
			temp = pointer2.next;
			pointer2.next = pointer1.next;
			pointer1.next = pointer2;
			pointer1 = pointer1.next.next;
			pointer2 = temp;
		}
		return;
	}
}


發佈了127 篇原創文章 · 獲贊 0 · 訪問量 9萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章