快上网专注成都网站设计 成都网站制作 成都网站建设
成都网站建设公司服务热线:028-86922220

网站建设知识

十年网站开发经验 + 多家企业客户 + 靠谱的建站团队

量身定制 + 运营维护+专业推广+无忧售后,网站问题一站解决

Java实现单向链表反转-创新互联

本文实例为大家分享了Java实现单向链表反转的具体代码,供大家参考,具体内容如下

创新互联专业成都做网站、成都网站建设,集网站策划、网站设计、网站制作于一体,网站seo、网站优化、网站营销、软文营销等专业人才根据搜索规律编程设计,让网站在运行后,在搜索中有好的表现,专业设计制作为您带来效益的网站!让网站建设为您创造效益。

1、实现代码

public class LinkedListTest {

 public static void main(String[] args) {
  Node A = new Node("A");
  Node B = new Node("B");
  Node C = new Node("C");
  Node D = new Node("D");
  Node E = new Node("E");
  Node F = new Node("F");
  A.next = B;
  B.next = C;
  C.next = D;
  D.next = E;
  E.next = F;
  print(A);

  LinkedListReversor reversor = LinkedListReversor.RECURSION;
  System.out.println(reversor.getStrategy() + ":");
  Node tmp = reversor.execute(A);
  print(tmp);

  reversor = LinkedListReversor.NO_RECURSION;
  System.out.println(reversor.getStrategy() + ":");
  print(reversor.execute(tmp));
 }

 private static void print(Node node) {
  while (node != null) {
   System.out.print(node.value);
   node = node.next;
   if (node != null) {
    System.out.print("->");
   } else {
    System.out.println();
   }
  }
 }

}

class Node {
 public String value;
 public Node next;

 public Node(String value) {
  this.value = value;
 }
}

enum LinkedListReversor {
 RECURSION("递归") {
  @Override
  public Node execute(Node node) {
   Node prev = null;
   if (node == null || node.next == null) {
    prev = node;
   } else {
    Node tmp = execute(node.next);
    node.next.next = node;
    node.next = null;
    prev = tmp;
   }
   return prev;
  }
 },
 NO_RECURSION("非递归") {
  @Override
  public Node execute(Node node) {
   Node prev = null;
   while (node != null) {
    Node tmp = node;
    node = node.next;
    tmp.next = prev;
    prev = tmp;
   }
   return prev;
  }
 };
 private String strategy;

 private LinkedListReversor(String strategy) {
  this.strategy = strategy;
 }

 public abstract Node execute(Node node);

 public String getStrategy() {
  return strategy;
 }
}

本文标题:Java实现单向链表反转-创新互联
文章来源:http://6mz.cn/article/ideds.html

其他资讯