1. 程式人生 > >【LeetCode】234. Palindrome Linked List

【LeetCode】234. Palindrome Linked List

Problem:

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?

題目:給定一個單鏈表,判斷是否為迴文?最好時間複雜度O(n),空間複雜度為 O(1)。

思路:除去要求,最簡單的方法則是用stack儲存第一次遍歷過的點,再第二次遍歷依次取出比較。即可;此時空間複雜度為O(n);

滿足要求的解法:將後半部分連結串列逆轉,指向中間節點。再兩端同時比較。最後最好將連結串列恢復成原始狀態;

程式碼1:利用stack

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

程式碼2:滿足時間複雜度O(n)和空間複雜度要求O(1)

class Solution {
	public boolean isPalindrome(ListNode head) {
		if (head == null || head.next == null)
			return true;
		ListNode node = head;
		//ListNode right = null;
		ListNode cur = head;
        // node最終指向中間節點
		while (cur.next != null && cur.next.next != null) {
			cur = cur.next.next;
			node = node.next;
		}
		cur = node.next;
		node.next = null;
		ListNode temp=null;
		while(cur!=null){
			temp=cur.next;
			cur.next=node;
			node=cur;
			cur=temp;
		}
		temp = node;	//儲存右區首節點
		cur = head;
		boolean ret = true;
		while(cur!=null&&node!=null){
			if(cur.val!=node.val){
				ret = false;
				break;
			}
			cur=cur.next;
			node=node.next;
		}
        /*
        
		cur=temp.next;
		temp.next=null;
		node = temp;
		//恢復連結串列原始狀態
		while(cur!=null){
			temp=cur.next;
			cur.next=node;
			node = cur;
			cur = temp;
		}*/

		return ret;
	}
}