单链表的重新排列

题目原型:

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

思想:

首先,半逆置化单链表,即从“中间”断开单链表,然后逆置后半部分链表,最后对两个链表进行合并。

代码如下:

public class ReorderList
{
	public ListNode reverseList(ListNode head)
	{
		if (head == null)
			return head;
		ListNode p, q, t;
		p = head;
		int len = 0;
		// 求得链表长度
		while (p != null)
		{
			len++;
			p = p.next;
		}
		p = head;
		q = p;
		for (int i = 0; i <= len; i++)
		{
			if (len % 2 == 1)
			{
				if (i == len / 2 + 1)
				{
					break;
				}
				q = p;
				p = p.next;
			} else
			{
				if (i == len / 2)
				{
					break;
				}
				q = p;
				p = p.next;
			}
		}
		// 半逆置链表
		q.next = null;
		q = p;
		if (p != null)
			p = p.next;
		if (p != null)
			t = p.next;
		else
			t = null;
		if (q != null)
			q.next = null;
		// System.out.println(q.val);
		while (p != null)
		{
			p.next = q;
			q = p;
			p = t;
			if (t != null)
				t = t.next;
		}
		// 插入
		p = head;
		if (q != null)
			t = q.next;// 此时q指向最后一个节点,也就是半逆置后的第一个节点
		while (q != null)
		{
			q.next = p.next;
			p.next = q;
			p = q.next;
			q = t;
			if (t != null)
				t = t.next;
			else
				t = null;
		}
		return head;
	}

	public void reorderList(ListNode head)
	{
		ListNode p;
		p = reverseList(head);
		while (p != null)
		{
			System.out.print(p.val + " ");
			p = p.next;
		}
	}

	public static void main(String[] args)
	{
		int N = 4;
		int i = 2;
		ListNode node;
		ListNode pre;
		ListNode head;
		pre = new ListNode(1);
		head = pre;
		while (i <= N)
		{
			node = new ListNode(i);
			pre.next = node;
			pre = node;
			i++;
		}
		ReorderList r = new ReorderList();
		r.reorderList(head);
	}
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值