package cn.wangss.demo;
/**
* 反转链表
* @author LiPeng
*
*/
public class Test {
public static Node Reverse(Node head){
Node current=head;
Node nextTemp=null;
Node prevTemp=null;
while(current!=null){
//保存当前节点的next引用到临时变量nextTemp,防止下一步更新当前节点的next引用
//为上一个节点时丢失未反转之前的next节点的引用。
nextTemp=current.getNext();
//将当前节点的next引用设置成上一个节点
current.setNext(prevTemp);
//更新prevTemp引用为当前节点
prevTemp=current;
//更新current引用为nextTemp,开始下一次循环
current=nextTemp;
}
return head;
}
public static void main(String[] args) {
Node node3=new Node("3", null);
Node node2=new Node("2", node3);
Node node1=new Node("1", node2);
//传入首节点 反转
Test.Reverse(node1);
Node current=node3;
while(current!=null){
System.out.println(current.getId());
current=current.getNext();
}
}
static class Node{
private String id;
private Node next;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public Node getNext() {
return next;
}
public void setNext(Node next) {
this.next = next;
}
public Node(String id, Node next) {
super();
this.id = id;
this.next = next;
}
}
}
反转链表Java实现
最新推荐文章于 2023-06-16 14:12:42 发布