Java语言实现,检查链表是否为回文,史上最祥细讲解,算法小白也能看懂

1.首先定义链表节点数据结构类

public class Node<T> {

      Node next = null;

      T data;

       Node(T data){

              this.data = data;

      }

}

2.直接进入算法整体,废话不多说,直接上代码

public class TestHuiwen {

public static void main(String[] args){

      Node<String> a = new Node<>("a");

      Node<String> b = new Node<>("b");

      Node<String> c = new Node<>("c");

      a.next = b;

      b.next = c;

      boolean isTrue = isHuiwen(a);

      System.out.print(isTrue);

}

public static boolean isHuiwen(Node<String> A){

      Node<String> fast = A;

      Node<String> slow = A;

      while(fast.next!=null && fast.next.next!=null){

            fast = fast.next.next;

            slow = slow.next;

      }

      Node<String> head = slow.next;

      //翻转Node过程

      Node<String> headNext = null;//保存当前节点的下一个节点

      Node<String> pre = null;//保存当前节点的前一个节点

      while(head!=null){

            headNext = head.next;

            head.next = pre;//当前节点的下个节点指向前一个节点

            pre = head;//将当前节点保存起来

            head = headNext;//当前节点向后移动

      }

//对比过程

      Node<String> n1 = pre;

      Node<String> n2 = A;

      while(n1!= null){

            if(!n1.data.equals(n2.data)){

      return false;

      }

      n1 = n1.next;

      n2 = n2.next;

}

      return true;

}

}

猜你喜欢

转载自blog.csdn.net/qq_28394359/article/details/83826955