zoukankan      html  css  js  c++  java
  • java实现链表逆置

    结点结构:

    1 public class Node {
    2     //Node结点的结构为值域:value 指针域:next,指向下一个元素
    3      Node next;
    4      Object value;}

    初始化各变量:

    Node pre=null;//指向当前节点的前一结点。第一个结点的前一结点为null;
    Node cur=list;//指向当前结点。初始化时指向第一个结点
    Node next=list;//用于缓存当前结点的下一结点

    更改各节点next值:

    while(cur!=null){
      next=cur.next;
      cur.next=pre;
      pre=cur;
      cur=next;            
    }

    程序代码:

     1 package algorithm;
     2 
     3 public class Node {
     4     //Node结点的结构为值域:value 指针域:next,指向下一个元素
     5      Node next;
     6      Object value;
     7      
     8     //结点构造函数1。只存结点值。
     9     public Node(Object value){
    10         this.value=value;
    11         this.next=null;
    12     }
    13     //结点构造函数2。指定结点值和指向的下一个值
    14     public Node(Node next,Object value){
    15         this.value=value;
    16         this.next=next;
    17     }
    18     //链表逆置
    19     public static Node reverseList(Node list){
    20         
    21         Node pre=null;//指向当前节点的前一结点。第一个结点的前一结点为null;
    22         Node cur=list;//指向当前结点。初始化时指向第一个结点
    23         Node next=list;//用于缓存当前结点的下一结点
    24         
    25         while(cur!=null){
    26             next=cur.next;
    27             cur.next=pre;
    28             pre=cur;
    29             cur=next;            
    30         }
    31         return pre;
    32     }
    33     
    34     //打印链表
    35     public static void printList(Node List){
    36         Node node=List;
    37         while (node!=null){
    38             System.out.println(node.value);
    39             node=node.next;
    40         }
    41     }
    42     
    43     public static void main(String[] args) {
    44         // TODO Auto-generated method stub
    45         //创建4个结点
    46         Node a1=new Node("Node1");
    47         Node a2=new Node("Node2");
    48         Node a3=new Node("Node3");
    49         Node a4=new Node("Node4");
    50         
    51         //创建链表List a1->a2->a3->a4
    52         a1.next=a2;
    53         a2.next=a3;
    54         a3.next=a4;
    55         a4.next=null;
    56         Node List=a1;
    57         System.out.println("original list:");
    58         Node.printList(List);
    59         List=Node.reverseList(List);
    60         System.out.println("list reversed:");
    61         Node.printList(List);
    62         
    63     }
    64 }
  • 相关阅读:
    Codeforces Round #411 (Div. 2)
    腾讯比赛资料
    AtCoder Beginner Contest 060
    hdu 5288 数学 ****
    hdu 1866 几个矩形面积的和 ***
    hdu 2232 矩阵 ***
    bzoj 1415 期望+记忆化搜索 ****
    hdu 5033 单调栈 ****
    hdu 3032 sg打表找规律 *
    hdu 2516 FIB博弈
  • 原文地址:https://www.cnblogs.com/newRedFlower/p/3379639.html
Copyright © 2011-2022 走看看