c_cpp 用于检查单链表是否为回文的功能

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了c_cpp 用于检查单链表是否为回文的功能相关的知识,希望对你有一定的参考价值。

//https://www.geeksforgeeks.org/find-length-of-loop-in-linked-list/
#include<bits/stdc++.h>
using namespace std;

struct linked_list {
    char data;
    struct linked_list* next;
};
typedef struct linked_list node;

node* insert(node* head, char n) {
    node* list = (node*)malloc(sizeof(node*));
    list->data=n;
    list->next=head;
    head=list;
    return head;
}

void print(node* head) {
    node* n = head;
    while (n != NULL) {
        cout<< n->data << "->";
        n = n->next;
    }
}

node* reverse(node* head) {
    node *prev = NULL, *current = head, *next=NULL;
    while (current != NULL) {
        next = current->next;
        current->next = prev;
        prev = current;
        current = next;
    }
    return prev;
}

void isPalindrome (node* head) {

    node *slow=head, *fast=head;
    if (head != NULL) {
        while (fast && fast->next) {
            fast = fast->next->next;
            slow = slow->next;
        }
    }

    if(fast == NULL) {
        slow = reverse(slow);
        while (slow != NULL) {
            if (slow->data != head->data) {
                cout<< "Not a palindrome\n";
                return;
            }
            slow = slow->next;
            head = head->next;
        }
        cout<< "Is a Palindrome!\n";
        return;
    }

    if (fast->next == NULL) {
        slow = reverse(slow->next);
        while (slow != NULL) {
            if (slow->data != head->data) {
                cout<< "Not a palindrome\n";
                return;
            }
            slow = slow->next;
            head = head->next;
        }
        cout<< "Is a Palindrome!\n";
        return;
    }
}

int main() {
    string s;
    cout<<"enter the string: ";
    cin>>s;
    int n = s.length();
    if (n == 1){
        cout<< "String length has to be more than 2...";
        exit(0);
    }
    node* head = NULL;

    for(int i=0;i<n;i++) {
        head = insert(head, s[i]);
    }
    print (head);
    cout<< "\n";
    isPalindrome(head);



}

以上是关于c_cpp 用于检查单链表是否为回文的功能的主要内容,如果未能解决你的问题,请参考以下文章

单链表字符串判断回文

如何在不使用额外空间的情况下检查双向链表是不是为回文?

判断回文

利用递归函数实现检查一个字符串是否为回文数

c_cpp 交替拆分给定的单链表

c_cpp 单链表的快速排序