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? 

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;
	}
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值