給定一個單鏈表 L:L0→L1→…→Ln-1→Ln ,
將其重新排列後變爲: L0→Ln→L1→Ln-1→L2→Ln-2→…
你不能只是單純的改變節點內部的值,而是需要實際的進行節點交換。
簡要題解:
定義一個vector然後把鏈表插入後直接根據vector操作即可簡要代碼如下:
/**
* 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)return;
vector<ListNode*>ve;
ListNode* cur=head;
while(cur)
{
ve.push_back(cur);
cur=cur->next;
}
int l=0,r=ve.size()-1;
while(l<r)
{
ve[l]->next=ve[r];
ve[r--]->next=ve[++l];
}
ve[l]->next=NULL;
}
};