zoukankan      html  css  js  c++  java
  • leetcode 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) 两部分,   reverse一个list. 再比較.

    [CODE]

    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) { val = x; }
     * }
     */
     
     // 1 2 3 2 1; 1 2 3 3 2 1;
    public class Solution {
        public boolean isPalindrome(ListNode head) {
            //input check  abcba abccba
            if(head==null || head.next==null) return true;
            
            ListNode middle = partition(head);
            middle = reverse(middle);
            
            while(head!=null && middle!=null) {
                if(head.val != middle.val) return false;
                head = head.next;
                middle = middle.next;
            }
            return true;
        }
        private ListNode partition(ListNode head) {
            ListNode p = head;
            while(p.next!=null && p.next.next!=null) {
                p = p.next.next;
                head = head.next;
            }
            
            p = head.next;
            head.next = null;
            return p;
        }
        private ListNode reverse(ListNode head) {
            if(head==null || head.next==null) return head;
            ListNode pre = head;
            ListNode cur = head.next;
            pre.next = null;
            ListNode nxt = null;
            
            while(cur!=null) {
                nxt = cur.next;
                cur.next = pre;
                pre = cur;
                cur = nxt;
            }
            return pre;
        }
    }



  • 相关阅读:
    1.tomcat部署项目的几种方式和weblogic部署方式及一点通讯
    C程序第二章节:算法
    java 代码第一天练习
    git生成公钥私钥
    sourceTree操作
    gradle插件安装
    gradle环境搭建
    bootstrap
    20170223
    大企业招聘真的是这样进行的吗?
  • 原文地址:https://www.cnblogs.com/lcchuguo/p/5318998.html
Copyright © 2011-2022 走看看