public class ReverseListTest {
static class Node {
public int num;
public Node next;
public Node(int n) {
this.num = n;
}
}
public static void main(String[] args) {
int[] src = new int[]{1, 2, 3, 4, 5};
Node head = arrayToNode(src);
printNode(head);
Node newHead = reverseList(head);
printNode(newHead);
}
public static Node arrayToNode(int[] arr) {
Node head = new Node(arr[0]); // 把数组的第一个位置定义为头结点
Node cur = head; // 一个指针,此时指向头结点
for (int i = 1; i < arr.length; i++) { //头结点已经定义,从1开始
//尾插法
Node newNode = new Node(arr[i]);
cur.next = newNode;
cur = cur.next;
}
return head;
}
public static Node reverseList(Node head) {
Node pre = null; //前指针节点
Node cur = head; //当前指针节点
Node next = null;
while (cur != null) {
next = cur.next; //临时保存当前节点的下一个节点
cur.next = pre; //当前节点指向前面一个节点
pre = cur; //前节点后移
cur = next; //当前节点后移
}
return pre;
}
public static void printNode(Node node) {
while (node != null) {
System.out.print(node.num + " ");
node = node.next;
}
System.out.println();
}
}
输出:
image.png