class Node{//构造一个链表
int val;
Node next;
public Node(int val){
this.val=val;
}
}
public class Nizhi {
public static Node nizhi(Node head) {//实现链表逆置
Node node = head;
Node pre = null;
while (node != null) {
Node next = node.next;
node.next = pre;
pre = node;
node = next;
}
return pre;
}
public static Node lianbiao(){//自己创建一个链表
Node n1=new Node(1);
Node n2=new Node(2);
Node n3=new Node(3);
Node n4=new Node(4);
n1.next=n2;
n2.next=n3;
n3.next=n4;
return n1;
}
public static void main(String[]args){//测试
Node head=lianbiao();
Node res=new Nizhi().nizhi(head);
for(Node cur=res;cur!=null;cur=cur.next){
System.out.print(cur.val);
}
}
}
测试反转链表
最新推荐文章于 2021-07-27 20:22:22 发布