Java教程

Java在循环链表的开头插入一个新节点

在此程序中,我们将创建一个循环链接列表,并将每个新节点插入到循环链接列表的开头名单。如果列表为空,则头和尾将指向新添加的节点。如果列表不为空,则将头的数据存储到临时节点temp中,并以新节点作为头。这个新头将指向临时节点。简而言之,新添加的节点将成为列表的第一个节点(头),而先前的head(临时)将成为列表的第二个节点。
在循环链接列表的开始处插入新节点的Java程序
将新节点插入列表的开头。
在循环链接列表的开头插入新节点的Java程序
New表示新添加的节点。较早的A是列表的头。将new添加到列表的开头时,new将成为新的标题,并且将指向先前的标题,即A。

算法

定义一个代表列表中节点的Node类。它有两个属性数据,下一个将指向下一个节点。 定义另一个用于创建循环链表的类,它具有两个节点: head和tail。它有两种方法: addAtStart()和display()。 addAtStart()会将节点添加到列表的开头: 首先检查head是否为空(空列表),然后将节点插入为head。 头部和尾部都将指向新添加的节点。 如果列表不为空,则新添加的节点将成为新的头,并且将指向先前的头。
a.display()将显示列表中存在的所有节点。
定义一个新节点"当前",该节点将指向头部。 打印current.data直到电流再次指向头。 当前每次迭代将指向列表中的下一个节点。

程序:

public class InsertAtStart {
    //Represents the node of list.
        public class Node{
        int data;
        Node next;
        public Node(int data) {
            this.data = data;
        }
    }
    //Declaring head and tail pointer as null.
        public Node head = null;
    public Node tail = null;
    //this function will add the new node at the end of the list.
        public void addAtStart(int data){
        //Create new node
            Node newNode = new Node(data);
        //Checks if the list is empty.
            if(head == null) {
            //if list is empty, both head and tail would point to new node.
                head = newNode;
            tail = newNode;
            newNode.next = head;
        }
        else {
            //Store data into temporary node
                Node temp = head;
            //New node will point to temp as next node
                newNode.next = temp;
            //New node will be the head node
                head = newNode;
            //Since, it is circular linked list tail will point to head.
                tail.next = head;
        }
    }
    //Displays all the nodes in the list
        public void display() {
        Node current = head;
        if(head == null) {
            System.out.println("List is empty");
        }
        else {
            System.out.println("Adding nodes to the start of the list: ");
            do{
                //Prints each node by incrementing pointer.
                    System.out.print(" "+ current.data);
                current = current.next;
            }
            while(current != head);
            System.out.println();
        }
    }
    public static void main(String[] args) {
        InsertAtStart cl = new InsertAtStart();
        //Adding 1 to the list
            cl.addAtStart(1);
        cl.display();
        //Adding 2 to the list
            cl.addAtStart(2);
        cl.display();
        //Adding 3 to the list
            cl.addAtStart(3);
        cl.display();
        //Adding 4 to the list
            cl.addAtStart(4);
        cl.display();
    }
}
输出:
Adding nodes to the start of the list:
1
Adding nodes to the start of the list:
2 1
Adding nodes to the start of the list:
3 2 1
Adding nodes to the start of the list:
4 3 2 1
昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4