您的位置:首页 > 其它

LeetCode Reorder List

2014-03-15 10:35 399 查看
/**
* Definition for singly-linked list.
* struct ListNode {
*     int val;
*     ListNode *next;
*     ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:

ListNode* reverse(ListNode* head) {
if (head == NULL) {
return NULL;
}
ListNode* pre = NULL;
ListNode* cur = head;
while (cur != NULL) {
ListNode* tmp = cur->next;
cur->next = pre;
pre = cur;
cur = tmp;
}
return pre;
}

void reorderList(ListNode *head) {
if (head == NULL || head->next == NULL) {
return;
}
int num = 0;
ListNode* cur = head;
while (cur != NULL) {
num++;
cur = cur->next;
}
// seperate list, find middle node as the head of the new list
int ridx = num / 2;
ListNode* rhead = NULL;
cur = head;
for (int i=0; true; i++) {
if (i == ridx - 1) {
rhead = cur->next;
cur->next = NULL;
break;
}
cur = cur->next;
}

rhead = reverse(rhead);

cur = head;
head = head->next;

cur->next = rhead;
cur = rhead;
rhead = rhead->next;

while (head != NULL && rhead != NULL) {
cur->next = head;
cur = head;
head = head->next;

cur->next = rhead;
cur = rhead;
rhead = rhead->next;
}
cur->next = rhead; // there must be only one node left(odd case) or NULL(even case)
}

};


这题跟Copy List with Random Pointer 那题类似在生成结果前都对原先的链表结构进行了调整,这里就是把链表的后半段给逆序了一下,这样我们就能轻松的取出节点对(0, n), (1, n-1)...了(序号是原先未修改时的,[0, n])

第二轮:

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

/**
* Definition for singly-linked list.
* struct ListNode {
*     int val;
*     ListNode *next;
*     ListNode(int x) : val(x), next(NULL) {}
* };
*/
// 10:26
class Solution {
public:
void reorderList(ListNode *head) {
if (head == NULL) {
return;
}
ListNode fakeHead(0);
fakeHead.next = head;
ListNode* slow = &fakeHead;
ListNode* fast = &fakeHead;
while (fast != NULL && fast->next != NULL) {
slow = slow->next;
fast = fast->next->next;
}
ListNode* second = slow->next;
slow->next = NULL;

ListNode* pre = NULL;
ListNode* cur = second;
while (cur != NULL) {
ListNode* tmp = cur->next;
cur->next = pre;
pre = cur;
cur = tmp;
}
ListNode* ahead = fakeHead.next;
ListNode* bhead = pre;

fakeHead.next = NULL;
ListNode* last = &fakeHead;

while (ahead != NULL && bhead != NULL) {
last->next = ahead;
last = ahead;
ahead = ahead->next;
last->next = bhead;
last = bhead;
bhead = bhead->next;
}
last->next = ahead;
}
};


取中间点的方法改进了一下
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: