143:Reorder List【链表】
题目链接:https://leetcode.com/problems/reorder-list/
/*题意:给出链表L: L0→L1→…→Ln-1→Ln
转换成 L0→Ln→L1→Ln-1→L2→Ln-2→…
*/
/**
*思路:将链表分成两段,分别为A和B,将B反转后插入A中
*/
class Solution {
public:
void show(ListNode *head) {
while(head != NULL) {
cout << head->val << " ";
head = head->next;
}
cout << endl;
}
int getListLength(ListNode *head) {
int res = 1;
while(head->next != NULL) {
res ++;
head = head->next;
}
return res;
}
//将链表分成两段A和B,返回B的头结点
//B的长度大于等于A的长度
ListNode* getRightListHead(ListNode *head, int k) {
for(int i = 1; i < k; i ++)
head = head->next;
ListNode *res = head->next;
head->next = NULL;
return res;
}
//反转链表
void RotateList(ListNode *&head) {
ListNode *root = new ListNode(0);
ListNode *cur = head;
while(cur != NULL) {
ListNode *next = cur->next;
cur->next = root->next;
root->next = cur;
cur = next;
}
head = root->next;
}
void InsertList(ListNode *&headA, ListNode *&headB) {
ListNode *curA = headA;
ListNode *curB = headB;
while(curA->next != NULL) {
ListNode *nextA = curA->next;
ListNode *nextB = curB->next;
curA->next = curB;
curB->next = nextA;
curA = nextA;
curB = nextB;
}
curA->next = curB;
}
void reorderList(ListNode* head) {
if(head == NULL) return;
int Length = getListLength(head);
if(Length <= 2) return;
ListNode *headA = head;
ListNode *headB = getRightListHead(head, Length>>1);
RotateList(headB);
InsertList(headA, headB);
head = headA;
}
};
浙公网安备 33010602011771号