• 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?

    解题思路:

    使用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) {
            ListNode end = head;
            ListNode mid = head;
            while(end != null && end.next != null){
            	end = end.next.next;
            	mid = mid.next;
            }
            if(end != null) //in case of odd list
            	mid = mid.next;
            mid = reverseList(mid);
            while(mid != null){
            	if(mid.val != head.val)
            		return false;
            	mid = mid.next;
            	head = head.next;
            }
            return true;
        }
    
        public ListNode reverseList(ListNode head){
        	ListNode pre = null, next = null;
        	while(head != null){
        		next = head.next;
        		head.next = pre;
        		pre = head;
        		head = next;
        	}
        	return pre;
        }
    }
    

      

  • 相关阅读:
    关于<form>标签
    javaEE学习随笔
    类与接口
    java学习中的一些总结
    java 对象的创建
    jQuery选择器
    CSS学习随笔
    JDBC笔记 二
    Java EE笔记 (1) JDBC
    泛型笔记
  • 原文地址:https://www.cnblogs.com/zihaowang/p/5184345.html
Copyright © 2020-2023  润新知