C语言 回文链表(给你一个单链表的头节点 head ,请你判断该链表是否为回文链表。如果是,返回 true ;否则,返回 false )

 思路:求出链表的长度,将链表前面一般的元素入栈,然后逐个出栈与后一半的元素进行比较,如果一旦不相等立马返回FALSE,停止比较,如果到最后栈不为空也要返回FALSE,只有当栈为空且出栈的元素和链表后一半的元素都想得才能返回TRUE;另外要注意的一点是长度为1的链表都是回文链表所以要进行特殊处理,即当length=1时直接返回TRUE不用进行后续的操作。

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
typedef struct stacknode
{
    int data;
    struct stacknode* next;
}stacknode;
int l(struct ListNode* head)
{
    struct ListNode* p=head;
    int i=0;
    while(p!=NULL)
    {
        i++;
        p=p->next;
    }
    return i;
}
void push(struct stacknode **s,int n)
{
    struct stacknode *p;
    p=(stacknode*)malloc(sizeof(stacknode));
    p->data=n;
    p->next=(*s);
    (*s)=p;
}
int pop(struct stacknode** s)
{
    int e=(*s)->data;
    (*s)=(*s)->next;
    return e;
}
int empty(struct stacknode* S)
{
    if(S==NULL)
    return 0;
    else
    return 1;
}
bool isPalindrome(struct ListNode* head){
    if(head==NULL)
    return false;
    struct stacknode* S;
    S=NULL;
    struct ListNode* p=head;
    int length=l(head);
    if(length==1)
    return true;
    for(int i=1;i<=length/2;i++)
    {
        push(&S,p->val);
        p=p->next;
    }
    if(length%2!=0)
        p=p->next;
    while(p!=NULL)
    {
        if(p->val==pop(&S))
        p=p->next;
        else 
        return false;
    }
    if(empty(S)==0&&p==NULL)
    return true;
    else
    return false;
}

运行结果:

  • 2
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值