欢迎访问宙启技术站
智能推送

通过Java函数实现链表的反转

发布时间:2023-10-31 17:26:14

链表是一种常见的数据结构,它由一系列节点组成,每个节点包含一个数据元素和一个指向下一个节点的指针。在链表中,节点的顺序是通过指针来定义的,而不是像数组一样通过索引来定义。

反转链表是指将链表中的节点顺序逆向排列。例如,对于链表1->2->3->4->5,反转后的链表为5->4->3->2->1。

下面是一个通过Java函数实现链表反转的示例代码:

class Node {
    int data;
    Node next;

    Node(int data) {
        this.data = data;
        this.next = null;
    }
}

class LinkedList {
    Node head;

    void reverse() {
        Node current = head;
        Node previous = null;
        Node next = null;

        while (current != null) {
            next = current.next;
            current.next = previous;
            previous = current;
            current = next;
        }

        head = previous;
    }

    void printList() {
        Node node = head;
        while (node != null) {
            System.out.print(node.data + " ");
            node = node.next;
        }
    }
}

public class Main {
    public static void main(String[] args) {
        LinkedList linkedList = new LinkedList();
        linkedList.head = new Node(1);
        linkedList.head.next = new Node(2);
        linkedList.head.next.next = new Node(3);
        linkedList.head.next.next.next = new Node(4);
        linkedList.head.next.next.next.next = new Node(5);

        System.out.println("Original list:");
        linkedList.printList();

        linkedList.reverse();

        System.out.println("
Reversed list:");
        linkedList.printList();
    }
}

以上代码中,我们首先定义了一个Node类来表示链表的节点,包含一个data成员变量和一个next指针指向下一个节点。接着定义了一个LinkedList类来表示链表,包含一个head成员变量指向链表的头节点。

reverse方法中,我们使用三个指针currentpreviousnext来逐个反转节点。初始时,current指向头节点,previousnext都为null。每次迭代,我们先保存当前节点的下一个节点到next,然后将当前节点的next指向previous,更新previous为当前节点,最后将current更新为next。当迭代完成后,将head指向新的链表的头节点即完成链表的反转。

printList方法中,我们通过迭代打印链表中每个节点的数据。

main函数中,我们创建了一个包含5个节点的链表,并调用reverse方法将其反转。最后通过调用printList方法打印出反转后的链表。

以上就是通过Java函数实现链表的反转的示例代码和解释。通过这个例子,我们可以清楚地理解链表反转的原理和实现方式。在实际应用中,链表的反转是一个常见的操作,可以帮助我们解决很多实际问题。