您的位置:首页 > 其它

[LeetCode]Reorder List

2014-10-21 15:21 337 查看
题目描述:

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

解题方案:

类似于将两个链表合成一个链表。1.首先利用快慢指针找到链表的中点,将链表分为两段;2.反转后一链表,合并两个链表。下面是该题代码:

class Solution {
public:
void reorderList(ListNode *head) {

if (head == NULL || head->next == NULL || head->next->next == NULL) {return;}
struct ListNode *fast = head;
struct ListNode *slow = head;

while(fast != NULL && fast->next != NULL) {
fast = fast->next->next;
slow = slow->next;
}

//cout <<slow->val;
struct ListNode *CurPos = slow->next;
slow->next = NULL;

//cout << CurPos->val;
//cout <<fast->val;
//反转链表
struct ListNode *PreCurPos = NULL;
struct ListNode *NextCurPos = CurPos->next;

while(CurPos != NULL) {
CurPos->next = PreCurPos;
//cout<<CurPos->val<<endl;
PreCurPos = CurPos;
if (NextCurPos == NULL) {
break;
}
CurPos = NextCurPos;
NextCurPos = CurPos->next;
}
slow = head;
head = merge(slow, CurPos);
}

ListNode *merge(ListNode *lhs, ListNode *rhs) {
ListNode *newhead = new ListNode(0);
ListNode *p = newhead;
int flag = 0;
while (lhs && rhs) {
if (flag == 0) {
p->next = lhs;
lhs = lhs->next;
flag = 1;
} else {
p->next = rhs;
rhs = rhs->next;
flag = 0;
}
p = p->next;
}
if (lhs == NULL) {
p->next = rhs;
} else {
p->next = lhs;
}
p = newhead->next ;
newhead->next = NULL;
delete newhead;
return p;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: