112 判断一个链表是否为回文结构-进阶
Table of Contents

ac

# 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 * check(list_node * head)
{
    //////在下面完成代码
    // 获取节点个数
    int cnt = 0;
    list_node *p = head;
    while(p != NULL){
        cnt ++;
        p = p->next;
    }

    list_node *pHead = new list_node();
    // 反转左部分,并获得右部分的开始
    int halfCnt = cnt / 2;
    p = head;
    list_node *pRight = head;
    for(int i=0;i<halfCnt;i++){
        list_node *pNext = p->next;

        p->next = pHead->next;
        pHead->next = p;

        pRight = pNext;
        p = pNext;
    }
    list_node *mid = pRight;
    if(cnt % 2 == 1){
        mid = pRight;
        pRight = pRight->next;
    }

    int flag = 1;
    p = pHead->next;
    while(pRight != NULL){
        if(pRight->val != p->val){
            flag = 0;
            break;
        }else{
            pRight = pRight->next;
            p = p->next;
        }
    }
    if(flag == 1){
        printf("true\n");
    }else{
        printf("false\n");
    }
    // 复原回去
    list_node *ansHead = new list_node();
    list_node *ansTail = ansHead;
    p = pHead->next;
    while(p != NULL){
        list_node *pNext = p->next;
        if(ansHead->next == NULL){
            p->next = ansHead->next;
            ansHead->next = p;
            ansTail = p;
        }else{
            p->next = ansHead->next;
            ansHead->next = p;
        }
        p = p->next;
    }
    ansTail->next = mid;
    return ansHead->next;
}


int main ()
{
    int L, R;
    list_node * head = input_list();
    check(head);
    return 0;
}