单链表实现链表逆序
约 272 字小于 1 分钟
2025-02-12
直接上代码,一些补充放在代码后面
package test;
public class Node {
public int value;
public Node next;
public Node(int i) {
value = i;
next = null;
}
/**
* 添加节点
* @param head 头节点
* @param add 新添加的节点
*/
public void add(Node head, Node add) {
if (head == null)
return;
while(head.next != null) {
head = head.next;
}
head.next = add;
}
/**
* 顺序打印
* @param head 头节点
*/
public static void print(Node head) {
if (head == null) {
System.out.println("链表是空的");
}
while(head != null) {
System.out.print(head.value + " ");
head = head.next;
}
}
/**
* 逆序打印
* @param head 头节点
*/
public static void reversePrint(Node head) {
if(head.next != null)
reversePrint(head.next);
System.out.print(head.value + " ");
}
/**
* 反转链表
* @param head 头节点
* @return
*/
public static Node reverse(Node head) {
if(head==null || head.next==null) return head;
Node p1 = head;
Node p2 = head.next;
p1.next = null;
while(p2.next != null) {
Node p3 = p2.next;
p2.next = p1;
p1 = p2;
p2 = p3;
}
p2.next = p1;
return p2;
}
}
package test;
public class NodeTest {
public static void main(String[] args) {
Node head = new Node(0);
for(int i=1;i<10;i++) {
head.add(head, new Node(i));
}
Node.reversePrint(head);//逆序打印
System.out.println();
Node.print(Node.reverse(head));//反转链表并顺序打印
}
}
重点说一下反转链表的思路