Leetcode 234. Palindrome Linked List

来源:互联网 发布:网络手势图片意思 编辑:程序博客网 时间:2024/06/11 19:42

234. Palindrome Linked List

Total Accepted: 69120 Total Submissions: 225579 Difficulty: Easy

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?

Hide Company Tags
 Amazon Facebook
Hide Tags
 Linked List Two Pointers
Hide Similar Problems
 (E) Palindrome Number (E) Valid Palindrome (E) Reverse Linked List

思路:

解法一:

n空间的做法是遍历到中间之后把slow.next开始的所有元素入栈。无论奇偶slow.next永远是要做对比的元素。然后做对比。

/** * Definition for singly-linked list. * public class ListNode { *     int val; *     ListNode next; *     ListNode(int x) { val = x; } * } */public class Solution { // 6ms    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;        }                Stack<Integer> st = new Stack<>();                fast = slow.next;        while(fast != null){            st.push(fast.val);            fast = fast.next;        }        while(!st.isEmpty()){            if(st.pop() != head.val) return false;            head = head.next;        }        return true;    }}

解法二:

常数空间。从以slow作为dummy head,把之后的元素翻转。然后slow = slow.next 在slow != null的时候和head元素对比。

/** * Definition for singly-linked list. * public class ListNode { *     int val; *     ListNode next; *     ListNode(int x) { val = x; } * } */public class Solution { // 2ms    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;        }        fast = slow.next; slow.next = null;        while(fast != null){            ListNode next = fast.next;            fast.next = slow.next;            slow.next = fast;            fast = next;        }                slow = slow.next;        while(slow !=null){            if(slow.val != head.val) return false;            slow = slow.next;            head = head.next;        }        return true;    }}


0 0
原创粉丝点击