码迷,mamicode.com
首页 > 其他好文 > 详细

Palindrome Linked List

时间:2016-03-24 09:57:44      阅读:176      评论:0      收藏:0      [点我收藏+]

标签:

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:创建一个ArrayList用于保存每个节点的value,遍历LinkedList将每个节点的value依次add到ArrayList中。

    利用双指针,一个在ArrayList的首部,一个在ArrayList的尾部,相向遍历看其value是否相等,如果不相等返回false,如果相遇则返回true。

其空间复杂度为O(n),时间复杂度为O(1).

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public boolean isPalindrome(ListNode head) {
          if (head == null || head.next == null) {
            return true;
        }
        ArrayList<Integer> list = new ArrayList<>();
        while (head != null) {
            list.add(head.val);
            head = head.next;
        }
        for (int i = 0, j = list.size() - 1; i < j; i++, j--) {
            if ((int)list.get(i) != (int)list.get(j)) {
                return false;
            }
        }
        return true;
    }
}

 思路2:将链表从中间节点之后的节点都翻转记为p2, 原链表到中间节点的部分记为p1.

           依次比较p1 与 p2 节点值是否相等。

 1 // This code would destroy the original structure of the linked list.
 2 // If you do not want to destroy the structure, you can reserve the second part back.
 3 public class Solution {
 4     /**
 5      * @param head a ListNode
 6      * @return a boolean
 7      */
 8     public boolean isPalindrome(ListNode head) {
 9         if (head == null) {
10             return true;
11         }
12         
13         ListNode middle = findMiddle(head);
14         middle.next = reverse(middle.next);
15         
16         ListNode p1 = head, p2 = middle.next;
17         while (p1 != null && p2 != null && p1.val == p2.val) {
18             p1 = p1.next;
19             p2 = p2.next;
20         }
21         
22         return p2 == null;
23     }
24     
25     private ListNode findMiddle(ListNode head) {
26         if (head == null) {
27             return null;
28         }
29         ListNode slow = head, fast = head.next;
30         while (fast != null && fast.next != null) {
31             slow = slow.next;
32             fast = fast.next.next;
33         }
34         
35         return slow;
36     }
37     
38     private ListNode reverse(ListNode head) {
39         ListNode prev = null;
40         
41         while (head != null) {
42             ListNode temp = head.next;
43             head.next = prev;
44             prev = head;
45             head = temp;
46         }
47         
48         return prev;
49     }
50 }

 

Palindrome Linked List

标签:

原文地址:http://www.cnblogs.com/FLAGyuri/p/5314003.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!