leetcode234. 回文链表(stack)

请判断一个链表是否为回文链表。

示例 1:

输入: 1->2
输出: false
示例 2:

输入: 1->2->2->1
输出: true

先全存在stack里面
然后把list和stack 的peek比较 count/2 次

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public boolean isPalindrome(ListNode head) {
       int count=0;
       Stack<Integer> stack=new Stack<>();
        ListNode cur=head; 
       while(cur!=null){
           count++;
           stack.push(cur.val);
           cur=cur.next;   
       } 
        cur=head; 
        for(int i=0;i<count/2;i++){
            if(cur.val!=stack.peek()){
                return false;
            }
            else{
                cur=cur.next;
                stack.pop();
            }
        }
       return true;    
    }
}

猜你喜欢

转载自blog.csdn.net/rudychan/article/details/94381627