leetcode234~Palindrome Linked List

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

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

思路: 判斷一個鏈表是否是迴文鏈表,幾種解法都會使用到倆指針,用來從中間分割鏈表。
1 將前部分的鏈表元素放入數組中,然後在遍歷後半部分的鏈表時,和數據中逆序元素進行比較
2 將前部分的鏈表元素放在list集合中,使用add(0,value)方法,每次都是從頭插入,然後比較
3 利用堆棧的先進後出特性
4 將後半部分鏈表原地翻轉

只有第四種的空間複雜度是O(1)

public class PalindromeLinkedList {
    public boolean isPalindrome(ListNode head) {
        if(head==null) return true;
        ListNode slow = head;
        ListNode fast = head;
        while(fast.next!=null && fast.next.next!=null) {
            slow = slow.next;
            fast = fast.next.next;
        }
        ListNode rhead = slow.next;
        slow.next = null;
        //對後半部分鏈表翻轉
        ListNode pre = null;
        while(rhead!=null) {
            ListNode tmp = rhead.next;
            rhead.next = pre;
            pre = rhead;
            rhead = tmp;
        }
        //此時pre是翻轉後的頭節點
        while(head!=null && pre!=null) {
            if(head.val!=pre.val) {
                return false;
            }
            head = head.next;
            pre = pre.next;
        }
        return true;
    }

    //使用堆棧實現
    public boolean isPalindrome2(ListNode head) {
        if(head==null) return true;
        Stack<Integer> stack = new Stack<Integer>();
        ListNode slow=head,fast=head;
        //將第一個元素進棧
        stack.push(slow.val);
        while(fast.next!=null && fast.next.next!=null) {
            slow = slow.next;
            fast = fast.next.next;
            //入棧
            stack.push(slow.val);
        }

        //這裏需要對鏈表長度進行判斷 如果爲奇數,則中間那個節點值也進棧了 如果爲偶數,則比較應該從下一個節點開始
        if(fast!=null) {
            slow = slow.next;
        }
        while(slow!=null) {
            if(slow.val!=stack.pop()) {
                return false;
            }
            slow = slow.next;
        }
        return true;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章