central list

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct Node {
    int data;
    struct Node* next;
} Node;

Node* createNode(int data) {
    Node* newNode = (Node*)malloc(sizeof(Node));
    newNode->data = data;
    newNode->next = NULL;
    return newNode;
}

void insertEnd(Node** head, int data) {
    Node* newNode = createNode(data);
    if (*head == NULL) {
        *head = newNode;
        return;
    }
    Node* temp = *head;
    while (temp->next != NULL) {
        temp = temp->next;
    }
    temp->next = newNode;
}

Node* reverseList(Node* head) {
    Node* prev = NULL;
    Node* curr = head;
    Node* next = NULL;
    while (curr != NULL) {
        next = curr->next;
        curr->next = prev;
        prev = curr;
        curr = next;
    }
    return prev;
}

int isPalindrome(Node* head) {
    if (head == NULL || head->next == NULL) {
        return 1;
    }
    Node* slow = head;
    Node* fast = head;
    while (fast->next != NULL && fast->next->next != NULL) {
        slow = slow->next;
        fast = fast->next->next;
    }
    Node* secondHalf = reverseList(slow->next);
    slow->next = NULL;
    Node* firstHalf = head;
    Node* temp = secondHalf;
    while (temp != NULL) {
        if (firstHalf->data != temp->data) {
            return 0;
        }
        firstHalf = firstHalf->next;
        temp = temp->next;
    }
    return 1;
}

int main() {
    char input[1024];
    fgets(input, sizeof(input), stdin);
    Node* head = NULL;
    char* token = strtok(input, ",");
    while (token != NULL) {
        if (strlen(token) > 0 && token[0] != '\n') {
            int num = atoi(token);
            insertEnd(&head, num);
        }
        token = strtok(NULL, ",");
    }
    if (isPalindrome(head)) {
        printf("Yes\n");
    } else {
        printf("No\n");
    }
    // Free the list
    Node* temp;
    while (head != NULL) {
        temp = head;
        head = head->next;
        free(temp);
    }
    return 0;
}

 

posted @ 2025-12-24 10:02  我不是青山  阅读(2)  评论(0)    收藏  举报