public class Node {
//Node结点的结构为值域:value 指针域:next,指向下一个元素
Node next;
Object value;
//结点构造函数1。只存结点值。
public Node(Object value){
this.value=value;
this.next=null;
}
//结点构造函数2。指定结点值和指向的下一个值
public Node(Node next,Object value){
this.value=value;
this.next=next;
}
//链表逆置
public static Node reverseList(Node list) {
Node pre = null;//指向当前节点的前一结点。第一个结点的前一结点为null;
Node cur = list;//指向当前结点。初始化时指向第一个结点
while (cur != null) {
Node nextTemp = cur.next;
cur.next = pre;
pre = cur;
cur = nextTemp;
}
return pre;
}
//打印链表
public static void printList(Node List){
Node node=List;
while (node!=null){
System.out.println(node.value);
node=node.next;
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
//创建4个结点
Node a1=new Node("Node1");
Node a2=new Node("Node2");
Node a3=new Node("Node3");
Node a4=new Node("Node4");
//创建链表List a1->a2->a3->a4
a1.next=a2;
a2.next=a3;
a3.next=a4;
a4.next=null;
Node List=a1;
System.out.println("original list:");
Node.printList(List);
List=Node.reverseList(List);
System.out.println("list reversed:");
Node.printList(List);
}
}
算法 链表逆置
于 2024-08-18 17:05:55 首次发布