234. 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、从中点开始反转链表,判断是否相等。

 

class Solution:

    def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:

         # reverse listb
        cur = head
        pre = None
        while cur:
            next = cur.next
            cur.next = pre
            pre = cur
            cur = next
        return pre
    def isPalindrome(self, head: Optional[ListNode]) -> bool:
        fake = ListNode(-1,head)
        pre = fake
        slow = fast = head
        
        while fast and fast.next:
            pre = pre.next
            slow = slow.next
            fast = fast.next.next
        
        pre.next = None

        lista = head
        listb = slow

        # reverse listb
        listb = self.reverseList(listb)

        #print(lista)
        #print(listb) 
        while lista and listb:
            if listb.val != lista.val:
                return False
            listb = listb.next
            lista = lista.next
       
        return True

 

 

 

 1 class Solution {
 2     public boolean isPalindrome(ListNode head) {
 3         ListNode faster= head ,slower= head;
 4         while(faster!=null && faster.next!=null){
 5             faster = faster.next.next;
 6             slower = slower.next;
 7         }
 8         if(faster!=null)
 9             //奇数
10             slower=slower.next;
11         ListNode newhead = Reverse(slower);
12         while(newhead!=null){
13             if(head.val!=newhead.val){
14                 return false;
15             }
16             head = head.next;
17             newhead = newhead.next;
18         }
19             return true;
20 
21     }
22 
23     public ListNode  Reverse(ListNode head) {
24         if(head == null ||head.next == null) return head;
25         ListNode pre = head;
26         head = head.next;
27         pre.next = null;
28         while(head != null){
29             ListNode next = head.next;
30             head.next = pre;
31             pre = head;
32             head = next;
33         }
34         return pre;
35     }
36 
37 }

 

posted @ 2017-09-23 22:46  乐乐章  阅读(270)  评论(0编辑  收藏  举报