Leetcode之Reorder List

题目:

Given a singly linked list LL0→L1→…→Ln-1→Ln,
reorder it to: L0→LnL1→Ln-1→L2→Ln-2→…

You may not modify the values in the list's nodes, only nodes itself may be changed.

Example 1:

Given 1->2->3->4, reorder it to 1->4->2->3.

Example 2:

Given 1->2->3->4->5, reorder it to 1->5->2->4->3.

代码:

方法一——使用map:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    void reorderList(ListNode* head) {
        if (!head)return;
	map<int, ListNode*> m;
	ListNode* p = head;
	int i = 0;
	while (p) {
		m[i] = p;
		p = p->next;
		i++;
	}
	int len = m.size();
	i = 0;
	for ( ;i < len/2; i++) {
		m[len - 1 - i]->next = m[i]->next;
		m[i]->next = m[len - i - 1];
	}
	m[i]->next = NULL;
	head = m[0];
    }
};

方法二——快慢指针、反转链表、合并:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    void reorderList(ListNode *head) 
    {
        if(head==NULL||head->next==NULL)
            return;
        //分成两段
        ListNode *preSlow=NULL;
        ListNode *slow=head,*fast=head;
        while(fast&&fast->next)
        {
            preSlow=slow;
            slow=slow->next;
            fast=fast->next->next;
        }  
        preSlow->next=NULL; //前半段

        //反转后半段
        ListNode *newBeg=slow;
        ListNode *last=newBeg->next;
        while(last)
        {
            ListNode *temp=last->next;
            last->next=newBeg;
            newBeg=last;
            last=temp;
        }
        slow->next=NULL;

        //合并
        fast=head;
        preSlow=NULL;
        while(fast) //注:以前半段为条件
        {
            ListNode *tem=newBeg->next;
            newBeg->next=fast->next;
            fast->next=newBeg;
            fast=newBeg->next;
            preSlow=newBeg;
            newBeg=tem;
        }
        if(newBeg !=NULL)   //因节点个数为奇数时,后段比前段多一个,所以最后要判断
            preSlow->next=newBeg;
    }
};

想法:

多看看别人的方法

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值