LeetCode 234——回文链表

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

示例 1:

输入: 1->2
输出: false

示例 2:

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

进阶:
你能否用 O(n) 时间复杂度和 O(1) 空间复杂度解决此题?

 

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public boolean isPalindrome(ListNode head) 
    {
        if(head==null)
            return true;
        if(head.next==null)
            return true;
        ListNode fast=head;
        ListNode slow=head;
        Stack stack=new Stack();
        while(fast.next!=null&&fast.next.next!=null)//最终slow指向链表中间节点
        {
            fast=fast.next.next;
            slow=slow.next;
        }
        //方法一、
        //下面slow继续后移同时入栈,把链表右半部分进栈
        while(slow.next!=null&&slow!=null)
        {
            stack.push(slow.next.val);
            slow=slow.next;
        }
        while(!stack.empty())
        {
            if(head.val!=Integer.parseInt(String.valueOf(stack.peek())))
                return false;
            head=head.next;
            stack.pop();
        }
        return true;
        
        
        //方法二、将右半部分链表倒置,依次比较前部分链表和后半部分链表
        /* ListNode tmp=slow.next;
        ListNode newhead=null;
        slow.next=null;
        //逆置后半段链表
        while(tmp!=null)
        {
            ListNode cur=tmp.next;
            tmp.next=newhead;
            newhead=tmp;
            tmp=cur;
        }
        //将两段链表进行比较
        while(newhead!=null)
        {
            if(newhead.val!=head.val)
            {
                return false;
            }
            newhead=newhead.next;
            head=head.next;
        }
        return true;*/


    }
}

算法思想:

1、根据回文链表的要求,首先利用快慢指针,找到链表的中间节点(偶数长度取前半部分的最后一个节点)。

2、接下来有两种办法进行链表值得比对:

方法一、从中间节点的下一节点开始,节点值进栈,接着栈中元素依次出栈和从头节点迭代开始的节点值进行比对,直至栈空,如果出现不同的值,直接返回false。

方法二、将链表的右半部分原地倒置(也可重新开辟一个链表存储,但这样空间复杂度增大了),接着比对链表的左右部分,返回结果true或false。

 

posted @ 2019-07-31 17:40  JiaMeng991010  阅读(94)  评论(0编辑  收藏  举报