Reorder List

Reorder List

  Total Accepted: 15732  Total Submissions: 78041 My Submissions

Given a singly linked list LL0L1→…→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}.

Have you been asked this question in an interview?  Yes

Discuss

这道题目,第一次见会感觉比较麻烦,以后见到了,就知道套路。先把链表截断,接着把链表的下半段反转,然后再把两个链表合并。截断链表的位置需要根据链表的长度来判断,奇数偶数稍有不同,自己找规律。整个过程没有改变链表节点的值,只是改变了其顺序,并且空间也是常数。

/**
 * Definition for singly-linked list.
 * class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {

	/**
	 * @param args
	 */
	/*
	public static void main(String[] args) {
		ListNode res,node = new ListNode(1);
		res = node;
		for(int i=2;i<=4;i++)
		{
			ListNode n = new ListNode(i);
			node.next = n;
			node = node.next;
		}
		Solution ss = new Solution();
		ss.reorderList(res);
		System.out.println(res);
	}
	*/
	public void reorderList(ListNode head){
		int len = getLen(head);
		if(len<3)
		{
			return;
		}
		int cut = (len+1)/2,count=1;
		ListNode h1 = head,h2 = null,h3 = null,h4=null;
		while(count<cut)
		{
			h1 = h1.next;
			count++;
		}
		h2 = h1.next;
		h1.next = null;
		h2 = reverseList(h2);
		ListNode res = new ListNode(-1);
		h1 = head;
		while(h1!=null&&h2!=null)
		{
			h3 = h1.next;
			h1.next = h2;
			h4 = h2.next;
			h2.next=h3;
			h1 = h3;
			h2 = h4;
		}
		return ;
	}
	ListNode reverseList(ListNode head)
	{
		ListNode n1,n2,n3;
		if(head==null||head.next==null)
		{
			return head;
		}
		n1 = head;
		n2 = n1.next;
		n1.next = null;
		while(n2!=null)
		{
			n3 = n2.next;
			n2.next = n1;
			n1 = n2;
			n2 = n3;
		}
		return n1;
	}
	int getLen(ListNode head)
	{
		int count = 0;
		while(head!=null){
			count++;
			head = head.next;
		}
		return count;
	}
}



你可能感兴趣的:(LeetCode,链表)