zoukankan      html  css  js  c++  java
  • [Algo] 306. Check If Linked List Is Palindrome

    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;
        
      }
    }
  • 相关阅读:
    预备作业03 20162308马平川
    预备作业02 20162308 马平川
    预备作业01
    采用dlopen、dlsym、dlclose加载动态链接库
    FastCGI协议分析
    Fastcgi协议定义解释与说明
    linux exec函数族
    进程通信---FIFO
    FTP协议及工作原理详解
    HTTP协议详解
  • 原文地址:https://www.cnblogs.com/xuanlu/p/12776616.html
Copyright © 2011-2022 走看看