Reorder List (leetcode)

题目:

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

题目来源:https://oj.leetcode.com/problems/reorder-list/

解题思路:如果用O(n)的空间来解,那么可以用vector保存所有向量,然后改变其next指针即可。如果用O(1)空间来解,则先把链表从中间分开,然后把后一部分的节点进行反转,最后把两个链表进行连接。

O(n)的空间的代码:

#include<iostream>
#include<vector>
using namespace std;

struct ListNode 
{
    int val;
    ListNode *next;
    ListNode(int x) : val(x), next(NULL) {}
};

void reorderList(ListNode *head)
{
	if(head==NULL)
		return ;
	vector<ListNode*> node;
	ListNode *curr=head;
	while(curr!=NULL)
	{
		node.push_back(curr);
		curr=curr->next;
	}
	curr=head;
	for(int i=0;i<(node.size()-1)>>1;i++)
	{
		node[node.size()-1-i]->next=curr->next;
		node[node.size()-2-i]->next=NULL;
		curr->next=node[node.size()-1-i];
		curr=curr->next->next;
	}
}
  
int main()  
{  
	ListNode *head=new ListNode(1);
	head->next=new ListNode(2);
	head->next->next=new ListNode(3);
	reorderList(head);

    system("pause");  
    return 0;  
}

O(1)空间算法:

#include<iostream>
#include<vector>
using namespace std;

struct ListNode 
{
    int val;
    ListNode *next;
    ListNode(int x) : val(x), next(NULL) {}
};

ListNode *reverse(ListNode *head)
{
	if(head==NULL)
		return NULL;
	ListNode *temp=new ListNode(-1);
	temp->next=head;
	ListNode *prev=temp;
	ListNode *curr=head;
	while(curr!=NULL)
	{
		ListNode *T=curr->next;
		curr->next=prev;
		prev=curr;
		curr=T;
	}
	delete temp;
	temp=NULL;
	head->next=NULL;
	return prev;
}

void reorderList(ListNode *head)
{
	if(head==NULL)
		return ;
	ListNode *first=head,*second=head;
	while(second!=NULL && second->next!=NULL)
	{
		first=first->next;
		second=second->next->next;
	}
	ListNode *temp=first;
	first=reverse(first->next);
	temp->next=NULL;
	ListNode *curr=head;
	while(first!=NULL)
	{
		ListNode *temp=curr->next;
		curr->next=first;
		first=first->next;
		curr->next->next=temp;
		curr=temp;
	}
}
  
int main()  
{  
	ListNode *head=new ListNode(1);
	head->next=new ListNode(2);
	head->next->next=new ListNode(3);
	head->next->next->next=new ListNode(4);
	reorderList(head);

    system("pause");  
    return 0;  
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值