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

[Algo] 306. Check If Linked List Is Palindrome

时间:2020-04-26 09:15:19      阅读:66      评论:0      收藏:0      [点我收藏+]

标签:tput   input   link   solution   The   must   his   fas   rom   

Given a linked list, check whether it is a palindrome.

Examples:

Input:   1 -> 2 -> 3 -> 2 -> 1 -> null

output: true.

Input:   1 -> 2 -> 3 -> null  

output: false.

Requirements:

Space complexity must be O(1)

 

/**
 * class ListNode {
 *   public int value;
 *   public ListNode next;
 *   public ListNode(int value) {
 *     this.value = value;
 *     next = null;
 *   }
 * }
 */
public class Solution {
  public boolean isPalindrome(ListNode head) {
    // Write your solution here
    if (head == null || head.next == null) {
      return true;
    }
    ListNode fast = head.next;
    ListNode slow = head;
    while (fast != null && fast.next != null) {
      fast = fast.next.next;
      slow = slow.next;
    }
    ListNode revHead = slow.next;
    ListNode cur = revHead;
    ListNode prev = null;
    while (cur != null) {
      ListNode nxt = cur.next;
      cur.next = prev;
      prev = cur;
      cur = nxt;
    }
    slow.next = prev;
    ListNode newRevHead = prev;
    while (head != null && newRevHead != null) {
      if (head.value != newRevHead.value) {
        return false;
      }
      head = head.next;
      newRevHead = newRevHead.next;
    }
    return true;
    
  }
}

 

[Algo] 306. Check If Linked List Is Palindrome

标签:tput   input   link   solution   The   must   his   fas   rom   

原文地址:https://www.cnblogs.com/xuanlu/p/12776616.html

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