234. Palindrome Linked List*

来源:互联网 发布:网络实践教程全部答案 编辑:程序博客网 时间:2024/06/01 23:18

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?

public class Solution {    public boolean isPalindrome(ListNode head) {        ListNode slow=head, fast=head;        while(fast!=null&&fast.next!=null){            slow = slow.next;            fast = fast.next.next;        }        slow = reverse(slow);        fast = head;        while(slow!=null){            if(fast.val!=slow.val) return false;            slow = slow.next;            fast = fast.next;        }        return true;    }    public ListNode reverse(ListNode head){        ListNode pre =null;        while(head!=null){            ListNode next = head.next;            head.next = pre;            pre = head;            head = next;        }        return pre;    }}
总结:把后半部分反转,然后和前半部分比较。比较巧妙的地方是找到linked list 中间位置的方法。

0 0
原创粉丝点击