您的位置:首页 > 其它

Reorder List (leetcode)

2014-11-18 17:42 393 查看
题目:

Given a singly linked list L: L0→L1→…→Ln-1→Ln,

reorder it to: L0→Ln→L1→Ln-1→L2→Ln-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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: