牛客-c语言刷题-判断一个链表是否为回文结构

题目连接:

判断一个链表是否为回文结构_牛客题霸_牛客网 (nowcoder.com)

题目描述:

描述

给定一个链表,请判断该链表是否为回文结构。

回文是指该字符串正序逆序完全一致。

数据范围: 链表节点数 0≤n≤105,链表中每个节点的值满足 ∣val∣≤107

题目解法:

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

/*
 *BM13 判断一个链表是否为回文结构
描述
    给定一个链表,请判断该链表是否为回文结构。
    回文是指该字符串正序逆序完全一致。
数据范围: 链表节点数  0≤n≤10^5
 ,链表中每个节点的值满足 |val| <= 10^7
 
*/

/**************************code*****************************************/
struct ListNode {
    int val;
    struct ListNode *next;
};

//使用模拟栈的方式,先遍历获得链表长度,然后malloc申请st,重新遍历把值装入st,在st中用索引来判断是否回文
bool isPail(struct ListNode* head ) {
    // write code here
    struct ListNode *tmp;
    int count = 0;
    long *st;
    tmp = head;
    while(tmp){         //遍历获得链表长度
        count++;
        tmp = tmp->next;
    }
    
    st = (long *)malloc(sizeof(long)*(count+1));    //malloc申请st
    tmp = head;
    count = 0;
    while(tmp){                         //重新遍历把值装入st
        st[count++]=tmp->val;
        tmp = tmp->next;
    }
    count--;
    for(int i=0; i<=count/2; i++){      //在st中用索引来判断是否回文
        if(st[i] != st[count-i]){
            free(st);
            return false;
        }
            
    }
    free(st);
    return true;
}

/**************************end******************************************/
void buildList(struct ListNode* head, int * input, int n){
    for(int i=0; i<n; i++){
        head->next = (struct ListNode*)malloc(sizeof(struct ListNode));
        head->val = input[i];
        head = head->next;
        head->next = NULL;
        head->val = 0;
    }
}

int main ()
{
    int input1[]={1,3,2,4,5};
    int input2[]={1,2,3,2,1};
    struct ListNode LNa, LNb;
    buildList(&LNa, input1, sizeof(input1)/sizeof(int));
    buildList(&LNb, input2, sizeof(input2)/sizeof(int));


    bool ret = isPail(&LNb);
    printf("\r\nret: %d", ret);
  

    return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值