zoukankan      html  css  js  c++  java
  • 234. Palindrome Linked List

    一、题目

      1、审题

      

      2、判断链表中的节点结构是否是回文形式。

    二、解答

      1、思路

        ①、采用两个指针 fast、slow向后移动,最终 slow 移动到了中间的位置(可能右边节点数多 1 个)

        ②、将 slow 右边的所有节点进行翻转,最终 slow 指向右端的起始节点,fast 指向 head

        ③、slow 与 fast 节点依次比较,若不相等,则返回false,若最终 slow == null,返回 true

     1     public boolean isPalindrome(ListNode head) {
     2         
     3         if(head == null || head.next == null)
     4             return true;
     5         
     6         ListNode fast = head, slow = head;
     7         while(fast != null && fast.next != null) {
     8             fast = fast.next.next;
     9             slow = slow.next;
    10         }
    11         if(fast != null) // odd nodes: let right half smaller
    12             slow = slow.next;
    13         
    14         slow = reverseList(slow);
    15         fast = head;
    16         
    17         while(slow != null) {
    18             if(fast.val != slow.val)
    19                 return false;
    20             slow = slow.next;
    21             fast = fast.next;
    22         }
    23         return true;
    24     }
    25     
    26     private ListNode reverseList(ListNode head) {
    27         ListNode prev = null;
    28         while(head != null) {
    29             ListNode next = head.next;
    30             head.next = prev;
    31             prev = head;
    32             head = next;
    33         }
    34         return prev;
    35     }
  • 相关阅读:
    C语言-第32课
    typeof和clamp
    C语言void*和*p的使用
    C语言二级指针和一级指针
    C语言结构体变量成员之指针变量成员的坑
    控制硬件三部曲
    C语言const char*使用
    jiffies是什么
    TPO3-1 Architecture
    相关关系|相关系数|线性关系|
  • 原文地址:https://www.cnblogs.com/skillking/p/9935669.html
Copyright © 2011-2022 走看看