Java在循环链接列表的末尾插入新节点
在此程序中,我们将创建一个循环链接列表,并在循环链接列表的末尾插入每个新节点名单。如果列表为空,则头和尾将指向新添加的节点。如果列表不为空,则新添加的节点将成为列表的新尾部。前一条尾巴将指向新节点作为其下一个节点。由于它是一个循环链表;新的尾巴将指向头部。换句话说,新节点将成为列表的最后一个节点(尾),而前一条尾将成为列表的倒数第二个节点。
身份矩阵
在列表末尾插入新节点后
New表示新添加的节点。 D是前一条尾巴。当将new添加到列表的末尾时,它将成为新的尾巴,D将指向new。
算法
定义一个代表列表中节点的Node类。它有两个属性数据,下一个将指向下一个节点。
定义另一个用于创建循环链表的类,它具有两个节点: head和tail。它有两种方法: addAtEnd()和display()。
addAtEnd()会将节点添加到列表的末尾: 首先检查head是否为空(空列表),然后将节点插入为head。 头部和尾部都将指向新添加的节点。 如果列表不为空,则新添加的节点将成为新的尾部,而先前的尾部将指向新节点作为其下一个节点。新的尾巴将指向头部。
a.display()将显示列表中存在的所有节点。
定义一个新节点"当前",该节点将指向头部。
打印current.data直到电流再次指向头。
当前每次迭代将指向列表中的下一个节点。
程序:
public class InsertAtEnd {
//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 addAtEnd(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 {
//tail will point to new node.
tail.next = newNode;
//New node will become new tail.
tail = newNode;
//Since, it is circular linked list tail will points 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 end 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) {
InsertAtEnd cl = new InsertAtEnd();
//Adding 1 to the list
cl.addAtEnd(1);
cl.display();
//Adding 2 to the list
cl.addAtEnd(2);
cl.display();
//Adding 3 to the list
cl.addAtEnd(3);
cl.display();
//Adding 4 to the list
cl.addAtEnd(4);
cl.display();
}
}
输出:
Adding nodes to the end of the list:
1
Adding nodes to the end of the list:
1 2
Adding nodes to the end of the list:
1 2 3
Adding nodes to the end of the list:
1 2 3 4