由节点组成的数据结构,每个节点都有数据和指针,指针指向下一个节点,称为链表,它与数组不同,当这种链表反转时,它是称为反向链表。其中链表分为两部分,称为链表的第一个节点和链表的其余部分,其中链表的其余部分调用反向函数,链表的其余部分链接到第一个节点,头指针固定。在本主题中,我们将学习 Java 中的反向链接列表。
开始您的免费软件开发课程
网络开发、编程语言、软件测试及其他
在java中可以使用两种算法来反转链表。他们是:
以下步骤描述了迭代算法的工作原理:
以下步骤描述了递归算法的工作原理:
以下是下面提到的示例
使用迭代算法反转单链表的 Java 程序
代码:
class List { static Node head1; static class Node { int data1; Node nex; Node(int d1) { data1 = d1; nex = null; } } //The linked list is reversed using this function Node reverselist(Node node1) { Node previous = null; Node curr = node1; Node nex = null; while (curr != null) { nex = curr.nex; curr.nex = previous; previous = curr; curr = nex; } node1 = previous; return node1; } // The contents of linked list are printed void printL(Node node1) { while (node1 != null) { System.out.print(node1.data1 + " "); node1 = node1.nex; } } public static void main(String[] args) { //The values to be inserted in the list before reversing are given here List l = new List(); l.head1 = new Node(30); l.head1.nex = new Node(40); l.head1.nex.nex = new Node(50); l.head1.nex.nex.nex = new Node(60); System.out.println("The items in the linked list that needs to be reversed are"); l.printL(head1); //Function to reverse the list is called here head1 = l.reverselist(head1); System.out.println(""); System.out.println("The items in the reversed linked list are"); l.printL(head1); } }
输出:
使用迭代算法反转单链表的 Java 程序
代码:
class List { static Node head1; static class Node { int data1; Node nex; Node(int d1) { data1 = d1; nex = null; } } // A recursive function to reverse the linked list Node reverse(Node current, Node previous) { //Last node is marked as head if (current.nex == null) { head1 = current; //previous node is updated with next current.nex = previous; return head1; } //current.nex node is saved for the recursive call Node nex1 = current.nex; //nex is updated current.nex = previous; reverse(nex1, current); return head1; } // Content of the reversed linked list are printed void printL(Node node) { while (node != null) { System.out.print(node.data1 + " "); node = node.nex; } } //Main method is called which prints the reversed linked list by calling the function public static void main(String[] args) { //The values to be inserted in the list before reversing are given here List list = new List(); list.head1 = new Node(20); list.head1.nex = new Node(30); list.head1.nex.nex = new Node(40); list.head1.nex.nex.nex = new Node(50); System.out.println("The items in the linked list that needs to be reversed are"); list.printL(head1); //Function to reverse the list is called here Node result = list.reverse(head1, null); System.out.println(""); System.out.println(""); System.out.println("The items in the reversed linked list are"); list.printL(result); } }
输出:
在本教程中,我们通过定义理解了链表反转的概念,并解释了链表反转的逻辑。讲解了两种反转链表的算法,这是一种迭代算法,并且讲解了递归算法以及用java实现算法的编程示例。
以上是Java中的反向链表的详细内容。更多信息请关注PHP中文网其他相关文章!