zoukankan      html  css  js  c++  java
  • 判断回文链表

    题目:

      给定一个链表,检查链表是否回文。

      思路:一种是将链表进行翻转(这里可以使用递归来解决,也可以使用非递归)然后翻转后的后半部分与链表的前半部分进行比较来进行判断,第二种是将先找到链表的中间位置,这里可以使用快慢指针来进行,快指针一次走两步,慢指针一次走一步,那么等到快指针走到末尾的时候那么慢指针的位置是链表的中间位置,然后再使用栈结构就能解决问题。

      代码:

     1 import java.util.Stack;
     2 
     3 public class 回文链表 {
     4     public static void main(String[] args) {
     5         ListNode node = new ListNode(1);
     6         node.next = new ListNode(2);
     7         node.next.next = new ListNode(32);
     8         node.next.next.next = new ListNode(32);
     9         node.next.next.next.next = new ListNode(2);
    10         node.next.next.next.next.next = new ListNode(1);
    11         System.out.println(isPalindrome(node));  // 输出true
    12     }
    13 
    14     public static boolean isPalindrome(ListNode pHead) {
    15         if (pHead == null)
    16             return false;
    17         if (pHead.next == null)
    18             return true;
    19         ListNode slower = pHead;
    20         ListNode faster = pHead;
    21         Stack<ListNode> stack = new Stack<>();
    22         boolean isOdd = true;
    23         while (faster != null && faster.next != null) {
    24             stack.push(slower);// 压栈
    25             slower = slower.next;
    26             faster = faster.next.next;
    27             if (faster == null) {
    28                 isOdd = false;
    29             }
    30         }
    31         // 奇数个结点,slower还要next一下
    32         if (isOdd)
    33             slower = slower.next;
    34         while (!stack.empty()) {
    35             if (stack.pop().val != slower.val) {// dequeue:弹出栈
    36                 return false;
    37             } else {
    38                 slower = slower.next;
    39             }
    40         }
    41 
    42         return true;
    43     }
    44     private static class ListNode {
    45         int val;
    46         ListNode next = null;
    47 
    48         ListNode(int val) {
    49             this.val = val;
    50         }
    51 
    52         @Override
    53         public String toString() {
    54             StringBuilder sb = new StringBuilder(val + "");
    55             ListNode nnext = next;
    56             while (nnext != null) {
    57                 sb.append(nnext.val);
    58                 nnext = nnext.next;
    59             }
    60             return sb.toString();
    61         }
    62     }
    63 }
  • 相关阅读:
    5285: [Hnoi2018]寻宝游戏
    CF 1117 E. Decypher the String
    4515: [Sdoi2016]游戏
    CF 1051 G. Distinctification
    4820: [Sdoi2017]硬币游戏
    HNOI2019游记
    最近公共祖先(LCT)
    [WC2006]水管局长(LCT)
    P4178 Tree(点分治)
    二维凸包
  • 原文地址:https://www.cnblogs.com/xiaoyh/p/10386850.html
Copyright © 2011-2022 走看看