161 按照左右半区的方式重新组合单链表
Table of Contents

ac

给定一个单链表的头部节点 head,链表长度为 N,如果 N 是偶数,那么前 N / 2 个节点算作左半区,后 N / 2 个节点算作右半区;如果 N 为奇数,那么前 N / 2 个节点算作左半区,后 N / 2 + 1个节点算作右半区。左半区从左到右依次记为 L1->L2->...,右半区从左到右依次记为 R1->R2->...,请将单链表调整成 L1->R1->L2->R2->... 的形式。
# include <bits/stdc++.h>
using namespace std;

struct list_node{
    int val;
    struct list_node * next;
};


list_node * input_list(void)
{
    int n, val;
    list_node * phead = new list_node();
    list_node * cur_pnode = phead;
    scanf("%d", &n);
    for (int i = 1; i <= n; ++i) {
        scanf("%d", &val);
        if (i == 1) {
            cur_pnode->val = val;
            cur_pnode->next = NULL;
        }
        else {
            list_node * new_pnode = new list_node();
            new_pnode->val = val;
            new_pnode->next = NULL;
            cur_pnode->next = new_pnode;
            cur_pnode = new_pnode;
        }
    }
    return phead;
}


list_node * relocate(list_node * head)
{
    //////在下面完成代码
    int n = 0;
    list_node* p = head;
    while(p != NULL){
        n ++;
        p = p->next;
    }
    p = head;
    int half = n / 2;
    while(half > 0){
        list_node* pNext = p->next;
        p = pNext;
        half --;
    }

    list_node* newHead = NULL;
    list_node* newTail = NULL;

    list_node* p1 = head;
    list_node* p2 = p;
    half = n / 2;
    while(half > 0){
        list_node* p1Next = p1->next;
        list_node* p2Next = p2->next;

        if(newHead == NULL){
            newHead = p1;
            newTail = newHead;
            newTail->next = NULL;
        }else{
            newTail->next = p1;
            newTail = p1;
            newTail->next = NULL;
        }
        newTail->next = p2;
        newTail = p2;
        newTail->next = NULL;

        p1 = p1Next;
        p2 = p2Next;
        half --;
    }
    if(n % 2 == 1){
        if(newHead == NULL){
            newHead = p2;
            newTail = newHead;
            newTail->next = NULL;
        }else{
            newTail->next = p2;
            newTail = p2;
            newTail->next = NULL;
        }
    }
    return newHead;
}

void print_list(list_node * head)
{
    while (head != NULL) {
        printf("%d ", head->val);
        head = head->next;
    }
    puts("");
}


int main ()
{
    list_node * head = input_list();
    list_node * new_head = relocate(head);
    print_list(new_head);
    return 0;
}