判断链表回文

来源:互联网 发布:php输出js代码 编辑:程序博客网 时间:2024/06/01 23:10


public class Palindrome {    public boolean isPalindrome(ListNode pHead) {        // write code here     ListNode slow = pHead, fast = pHead;    Stack<Integer> stack = new Stack<Integer>();    //快慢指针把前半截压栈    while(fast != null && fast.next != null){    stack.push(slow.val);    slow = slow.next;    fast = fast.next.next;    }    //奇数个节点    if(fast != null){    slow = slow.next;    }       while(slow != null){       if(slow.val!=stack.pop())       return false;           slow = slow.next;                  }       return true;    }}

题目描述

请编写一个函数,检查链表是否为回文。

给定一个链表ListNode* pHead,请返回一个bool,代表链表是否为回文。

测试样例:
{1,2,3,2,1}
返回:true
{1,2,3,2,3}
返回:false
原创粉丝点击