题解 | #判断一个链表是否为回文结构#

判断一个链表是否为回文结构

https://www.nowcoder.com/practice/3fed228444e740c8be66232ce8b87c2f

C语言:使用模拟栈的方式,先遍历获得链表长度,然后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;

}

全部评论

相关推荐

点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务