class Node {
public int value;
public Node next;
public Node(int value){
this.value=value; }
}
class Solve {
public Node reverseList(Node head) {
if (head == null) {
return null;
}
Node n1 = null;
Node n2 = head;
Node n3 = head.next;
while (n2 != null) {
n2.next = n1;
n1 = n2;
n2 = n3;
if (n3 != null) {
n3 = n3.next;
}
}
return n1;
}
}
public class CC {
public static void display(Node head) {
for (Node cur= head; cur != null;cur=cur.next){
System.out.print(cur.value + " ");
}
System.out.println();
}
public static void testReverseList() {
System.out.println("测试反转链表");
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;
Solve s = new Solve();
Node result = s.reverseList(n1);
display(result);
}
public static void main(String[] args) {
testReverseList();
}
}
【Java】实现链的反转
最新推荐文章于 2021-11-23 16:52:31 发布