zoukankan      html  css  js  c++  java
  • 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?

    先用2 pointer查找到中间点,然后后半部分reverse, 最后从head与中间点开始挨个check。此处要注意奇偶。

    public bool IsPalindrome(ListNode head) {
             if(head == null) return true;
             ListNode slow = head;
             ListNode fast = head;
             ListNode nextNode = null;
             ListNode newHead = null;
             
             //get middle pointer of the linked list
             while(fast != null && fast.next != null)
             {
                 slow = slow.next;
                 fast = fast.next.next;
             }
             
              while(slow != null)
                 {
                     nextNode = slow.next;
                     slow.next = newHead;
                     newHead = slow;
                     slow = nextNode;
                 }
             while(head != null && newHead != null)
             {
                 if(head.val != newHead.val) return false;
                 head = head.next;
                 newHead = newHead.next;
             }
             return true;
         }
  • 相关阅读:
    pytroch tensor初始化权重、改变tensor某行列为指定值
    蜜蜂寻路
    童年生活二三事
    母牛的故事
    星际密码
    斐波那契凤尾
    客似云来
    养兔子
    NowCoder数列
    采花生
  • 原文地址:https://www.cnblogs.com/renyualbert/p/5867926.html
Copyright © 2011-2022 走看看