在线编程--回文链表

题目描述

请编写一个函数,检查链表是否为回文。
给定一个链表ListNode* pHead,请返回一个bool,代表链表是否为回文。
测试样例:
{1,2,3,2,1}
返回:true
{1,2,3,2,3}
返回:false

import java.util.*;
/*
public class ListNode {
    int val;
    ListNode next = null;

    ListNode(int val) {
        this.val = val;
    }
}*/
public class Palindrome {
    public boolean isPalindrome(ListNode pHead) {
        // write code here
            // write code here
        int length = 0;   //链表长度
        ListNode pHeadlength = pHead;
        while (pHeadlength.next != null) {
            length++;
            pHeadlength = pHeadlength.next;
        }
        length++;   

        Stack<Integer> stack = new Stack<Integer>();
        if (length % 2 == 1) {  //如果是奇数个,中间节点不存
            for (int i = 0; i < length / 2; i++) {
                stack.push(pHead.val);
                pHead = pHead.next;
            }
            pHead = pHead.next;
        } else {
            for (int i = 0; i < length / 2; i++) {
                stack.push(pHead.val);
                pHead = pHead.next;
            }
        }
        while (pHead != null) {
            if (pHead.val != stack.pop()) {
                return false;
            }
            pHead=pHead.next;
        }
        return true;   
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值