Java从双向链表的开头删除新节点
Java程序,从双向链接列表的开头删除一个新节点
在此程序中,我们将创建一个双向链接列表,并从双向链接列表的开头删除一个节点清单。如果列表为空,则打印消息"列表为空"。如果列表不为空,那么我们将使头部指向列表中的下一个节点;我们将删除第一个节点。
考虑上面的示例,其中new是列表的头。使头指向列表中的下一个节点。现在,节点1将成为列表的新头,从而删除节点new。
算法
定义一个代表列表中节点的Node类。它将具有三个属性: 数据,前一个将指向上一个节点,下一个将指向下一个节点。
定义另一个用于创建双向链表的类,它有两个节点: head和tail。最初,头和尾将指向null。
deleteFromStart()将从列表的开头删除一个节点: 首先检查head是否为null(空列表),然后由于列表中没有节点,它将从函数返回。 如果列表不为空,它将检查列表是否只有一个节点。 如果列表中只有一个节点,则会将head和tail都设置为null。 如果列表中有多个节点,则头部将指向列表中的下一个节点并删除旧的头部节点。
a.display()将显示列表中存在的所有节点。
定义一个新节点"当前",该节点将指向头部。
打印current.data直到current指向null。
当前每次迭代将指向列表中的下一个节点。
程序:
public class DeleteStart
{
//Represent a node of the doubly linked list
class Node{
int data;
Node previous;
Node next;
public Node(int data) {
this.data = data;
}
}
//Represent the head and tail of the doubly linked list
Node head, tail = null;
//addNode() will add a node to the list
public void addNode(int data) {
//Create a new node
Node newNode = new Node(data);
//if list is empty
if(head == null) {
//Both head and tail will point to newNode
head = tail = newNode;
//head's previous will point to null
head.previous = null;
//tail's next will point to null, as it is the last node of the list
tail.next = null;
}
else {
//newNode will be added after tail such that tail's next will point to newNode
tail.next = newNode;
//newNode's previous will point to tail
newNode.previous = tail;
//newNode will become new tail
tail = newNode;
//As it is last node, tails next will point to null
tail.next = null;
}
}
//deleteFromStart() will delete a node from the beginning of the list
public void deleteFromStart() {
//Checks whether list is empty
if(head == null) {
return;
}
else {
//Checks whether the list contains only one element
if(head != tail) {
//head will point to next node in the list
head = head.next;
//Previous node to current head will be made null
head.previous = null;
}
//if the list contains only one element
//then, it will remove node and now both head and tail will point to null
else {
head = tail = null;
}
}
}
//display() will print out the nodes of the list
public void display() {
//Node current will point to head
Node current = head;
if(head == null) {
System.out.println("List is empty");
return;
}
while(current != null) {
//Prints each node by incrementing the pointer.
System.out.print(current.data + " ");
current = current.next;
}
System.out.println();
}
public static void main(String[] args) {
DeleteStart dList = new DeleteStart();
//Add nodes to the list
dList.addNode(1);
dList.addNode(2);
dList.addNode(3);
dList.addNode(4);
dList.addNode(5);
//Printing original list
System.out.println("Original List: ");
dList.display();
while(dList.head != null) {
dList.deleteFromStart();
//Printing updated list
System.out.println("Updated List: ");
dList.display();
}
}
}
输出:
Original List:
1 2 3 4 5
Updated List:
2 3 4 5
Updated List:
3 4 5
Updated List:
4 5
Updated List:
5
Updated List:
List is empty