Palindrome Linked List

Given a singly linked list, determine if it is a palindrome.

Example 1:

Input: 1->2
Output: false

Example 2:

Input: 1->2->2->1
Output: true

Time: O(N) Space: O(N) 

/**
 * 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 || head.next == null) return true;
        Stack<Integer> stack = new Stack<Integer>();
        
        ListNode node = head;
        while(node!=null){
            stack.push(node.val);
            node = node.next;
        }
        
        node = head;
        while(stack.size()!= 0 && stack.peek() == node.val){
            stack.pop();
            node = node.next;
        }
        return stack.size() == 0 && node == null;
    }
}

Follow up:
Could you do it in O(n) time and O(1) space?

思路:用双指针,找到中点,然后翻转后面的linkedlist,然后两段linkedlist分别走,如果不相等则返回false。

值得一提的是:长度的奇偶情况,reverse之后,并不需要完全一样,因为有一个长度比较长,只要前面的走完一致就可以了,最后一个点不需要相同,可以相同也可以一个为null,一个为数;

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public boolean isPalindrome(ListNode head) {
        if(head == null || head.next == null) {
            return true;
        }
        ListNode dummpy = new ListNode(-1);
        dummpy.next = head;
        
        ListNode slow = dummpy;
        ListNode fast = dummpy;
        
        while(fast != null && fast.next != null) {
            slow = slow.next;
            fast = fast.next.next;
        }
        ListNode newhead = slow.next;
        ListNode nhead = reverseLinkedList(newhead);
        return compareTwoList(head, nhead);
    }
    
    //最重要的是,奇数和偶数的情况,并不需要最后一致走完,也就是奇数的情况,1 2 1, reverse完之后,比较1就可以了
    private boolean compareTwoList(ListNode n1, ListNode n2) {
        while(n1 != null && n2 != null) {
            if(n1.val != n2.val) {
                return false;    
            }
            n1 = n1.next;
            n2 = n2.next;
        }    
        return true; // 这里直接return true很关键;
    }
    
    private ListNode reverseLinkedList(ListNode head) {
        ListNode dummpy = new ListNode(-1);
        dummpy.next = head;
        ListNode cur = head;
        
        while(cur != null && cur.next != null) {
            ListNode curnext = cur.next;
            cur.next = curnext.next;
            curnext.next = dummpy.next;
            dummpy.next = curnext;
        } 
        return dummpy.next;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值