题目:
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}.
题意:
给定一个链表,进行重排序,本来的链表是L0→L1→…→Ln-1→Ln,
重排序后的链表是L0→Ln→L1→Ln-1→L2→Ln-2→…。
思路:
注意到题目中要求不准改变节点的值。
由题目可知,需要将后面半段的节点插入到前面半段里去。并且是从尾部往前,可以用栈将后半段的元素装入,然后出栈顺序就变成了从尾部往前依次出栈。
我使用的方法是将后面半段进行反向排序,其本质是一样的。看面试官要求是否可以使用栈。
然后依次插入即可。
以上所述。
代码如下:
/**
* 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;
int count = 0;
ListNode* tmp = head;
while(tmp != NULL) {
count++;
tmp = tmp->next;
}
tmp = head;
ListNode* past = NULL;
for(int i = 0; i < (count + 1)/2; i++) {
past = tmp;
tmp = tmp->next;
}
past->next = NULL;
reverseList(tmp);
ListNode* h = head;
while(tmp != NULL) {
ListNode* next = h->next;
ListNode* tmpNext = tmp->next;
h->next = tmp;
h = next;
tmp->next = next;
tmp = tmpNext;
}
}
void reverseList(ListNode* &head) {
ListNode* past = NULL;
while(head != NULL) {
ListNode* next = head->next;
head->next = past;
past = head;
head = next;
}
head = past;
}
};