Reorder List

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

这个题如果不考虑空间复杂度,就简单多了,可以逆序复制保存一份,然后进行插入或合并,知道遇到相同的结点。很明显这不是题的本意。

这个题能想到的考察点有3个:
1)不同于数组或其他的容器类,不能直接获取总长度,所以不能直接获取到折半的分割点。想想判断一个链表是否存在环的问题,一种思路是令一个指针每次移动两步,一个移动一步,当二者再次相遇,我们就说环存在。就像长跑比赛的“套圈”。这里我们也设定两个指针,一个每次移动2步,一个移动1步,当两步的走到头的时候,一步的走了一半。

2)单向链表的就地逆置。

3)两个链表的合并,或者将链表A插入到链表B中。

//code

class Solution {
public:
	void reorderList(ListNode *head) {
		if(head == NULL || head->next == NULL)
			return;
		//find the half point
		ListNode *pfast, *pslow;
		pfast = pslow = head;
		while (pfast->next)
		{
			pfast = pfast->next;
			if(pfast->next)
				pfast = pfast->next;
			else
				break;
			pslow = pslow->next;
		}
		ListNode *head2 = pslow->next;
		pslow->next = NULL;
		//reverse head2
		ListNode *p2 = head2;
		ListNode *pre = NULL;
		while(p2)
		{
			ListNode *p_next = p2->next;
			p2->next = pre;
			pre = p2;
			p2 = p_next;
		}
		head2 = pre;
		ListNode *p1 = head;
		ListNode *q1,*p2,*q2;
		p2 = head2;
		//union the lists.
		while (p2)
		{
			q1 = p1->next;
			q2 = p2->next;
			p1->next = p2;
			p2->next = q1;
			p2 = q2;
			p1 = q1;
		}
		
	}
};


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值