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

  算法专题导航页面


【题目描述】
    给定一个链表,请判断该链表是否为回文结构。

【输入描述】
    n 表示链表的长度。
    val 表示链表节点的值

【输出描述】
    如果为回文结构输出 “true” , 否则输出 “false”。


【示例1】
    输入
        5
        1 2 3 2 1
    输出
        true


【备注】
     1<= n <= 2000000
     -1000000<= val <= 1000000


【代码实现 - CPP版】

# include <bits/stdc++.h>
using namespace std;

// link list node define
struct list_node{
    int val;
    struct list_node * next;
};

// create a link list
list_node * input_list(void)
{
    int n, val;
    
    list_node * phead = new list_node();
    list_node * cur_pnode = phead;
    
    cin >> n;
    for (int i = 1; i <= n; ++i) {
        cin >> val;
        if (i == 1) {
            cur_pnode->val = val;
            cur_pnode->next = NULL;
        }
        else {
            list_node * new_pnode = new list_node();
            new_pnode->val = val;
            new_pnode->next = NULL;
            
            cur_pnode->next = new_pnode;
            cur_pnode = new_pnode;
        }
    }
    return phead;
}

void check(list_node * head)
{
    /* based on data structure stack, only push the right part elements of a link list */
    // empty link list or only one element
    if(NULL == head || NULL == head->next) {
        cout << "true";
        return;
    }
    
    // node number >= 2
    list_node *cur = head;
    list_node *right = head->next;
    while(NULL != cur->next && NULL != cur->next->next) {
        right = right->next;
        cur = cur->next->next; // skip two units each time
    }
    
    // init a stack and push element pointed by pointer right
    stack<list_node*> s;
    while(NULL != right) {
        s.push(right);
        right = right->next;
    }
    
    // diff between top() and pop()
    while(!s.empty()) {
        if(s.top()->val != head->val) {
            cout << "false";
            return;
        }
        s.pop();
        head = head->next;
    }
    cout << "true";

}


int main ()
{
    list_node * head = input_list();
    check(head);
    return 0;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值