怎么用java递归实现单链表反转

   2025-02-13 7850
核心提示:使用递归来反转单链表需要使用两个指针,一个用来指向当前节点,另一个用来指向当前节点的前一个节点。递归的终止条件是当前节点

使用递归来反转单链表需要使用两个指针,一个用来指向当前节点,另一个用来指向当前节点的前一个节点。递归的终止条件是当前节点为null,即已经反转到链表的尾部。

以下是使用递归实现单链表反转的Java代码:

class Node {    int data;    Node next;    Node(int data) {        this.data = data;        next = null;    }}class LinkedList {    Node head;    LinkedList() {        head = null;    }    // 递归反转链表    Node reverse(Node currentNode, Node previousNode) {        // 递归终止条件        if (currentNode == null) {            return previousNode;        }        // 保存当前节点的下一个节点        Node nextNode = currentNode.next;        // 将当前节点的next指针指向前一个节点        currentNode.next = previousNode;        // 递归反转剩余部分        return reverse(nextNode, currentNode);    }    // 插入节点到链表尾部    void insert(int data) {        Node newNode = new Node(data);        if (head == null) {            head = newNode;        } else {            Node currentNode = head;            while (currentNode.next != null) {                currentNode = currentNode.next;            }            currentNode.next = newNode;        }    }    // 打印链表    void printList(Node node) {        while (node != null) {            System.out.print(node.data + " ");            node = node.next;        }    }    public static void main(String[] args) {        LinkedList list = new LinkedList();        list.insert(1);        list.insert(2);        list.insert(3);        list.insert(4);        System.out.println("原始链表:");        list.printList(list.head);        // 反转链表        list.head = list.reverse(list.head, null);        System.out.println("\n反转后的链表:");        list.printList(list.head);    }}

输出结果为:

原始链表:1 2 3 4反转后的链表:4 3 2 1

 
 
更多>同类维修知识
推荐图文
推荐维修知识
点击排行
网站首页  |  关于我们  |  联系方式  |  用户协议  |  隐私政策  |  网站留言