c - 检查链表是否回文的问题

标签 c singly-linked-list

我正在尝试使用以下方法检查链接是否为回文:

1) 创建并读取来自用户的原始链表。 2)遍历原链表,利用链表的栈实现对原链表进行逆向。 3) 初始化 flag = 1。遍历两个链表并比较每个节点,如果任何两个节点数据不匹配则中断循环并打印“Not Palindrome”,否则打印“Palindrome”。

程序如下:

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

int flag = 1;

struct node {
    int data;
    struct node *next;
}*start = NULL, *head = NULL;

void create() {
    char ch;

    do {
        struct node *new_node, *prev;
        new_node = (struct node*)malloc(sizeof(struct node));
        printf("Please Enter The Data: ");
        scanf("%d", &new_node->data);
        new_node->next = NULL;
        if(start == NULL) {
            start = new_node;
        } else {
            prev->next = new_node;
        }
        prev = new_node;
        printf("Do You Still Want To Insert(y/n)? ");
        fflush(stdin);
        scanf("%c", &ch);
    }while(ch != 'n');
}

void reverse() {
    struct node *current;
    current = start;
    while(current != NULL) {
        struct node *new_node, *prev;
        new_node = (struct node*)malloc(sizeof(struct node));
        new_node->data = current->data;
        new_node->next = NULL;
        if(head == NULL) {
            head = new_node;
        } else {
            new_node->next = head;
            head = new_node;
        }
        prev = new_node;
        current = current->next;
    }

}

int checkPal() {
    struct node *current1, *current2;
    current1 = start;
    current2 = head;
    while(current1 != NULL && current2 != NULL) {
        if(current1->data != current2->data) {
            flag = 0;
            break;
        }
        current1 = current1->next;
        current2 = current2->next;
    } 
    if(flag = 1)
        return 1;
    else
        return 0;
}

void display(struct node *list) {
    while(list != NULL) {
        printf("%d --> ", list->data);
        list = list->next;
    }
    printf("NULL\n");
}

int main() {
    create();
    printf("The original linked list is: \n");
    display(start);
    reverse();
    printf("The reversed linked list is: \n");
    display(head);
    if(checkPal()) {
        printf("The Linked List Is Palindrome!\n");
    } else {
        printf("The Linked List Is Not Palindrome!\n");
    }
}

但是,我总是得到“链表是回文!”即使不是!我做错了什么?

注意:只能用单链表完成。

最佳答案

所以你这里有错误

 if(flag = 1)
        return 1;
 else
        return 0;

这应该是:if(flag == 1)。使用您的代码,您不是在检查 flag 的值,而是将 1 分配给 flag 但是您可以通过简单地返回标志来简化它:

return flag

另外,我没有扫描你所有的代码,但我相信 flag 不需要是全局的,因为它只在你的 checkPal() 中使用函数,因此您只能在那里声明和初始化它。

关于c - 检查链表是否回文的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39307492/

相关文章:

c - MPI vector 乘法

c++ - 提高从数组向链表插入元素的性能

c - 如何使用链表在一个节点中存储两个实数

c - 字符串比较函数循环中的“while”循环超出必要

php - 添加源以构建 php 扩展

c - 前缀运算符和后缀运算符有什么区别?

c# - 从 C 程序到 C# 的数据传输

c++ - 链表数组(5 个队列)

C - 从单链表中删除元素

c - 链表在打印时仅显示第一个节点元素