Define Linked-List and Single Linked List. Write java program to perform a) Declare Node b) Add item in the Node c) Display the entire List d) Add Item at Start e) Add Item at End
时间: 2024-03-04 20:48:52 浏览: 62
A linked list is a data structure that consists of a sequence of nodes, where each node contains a value and a reference to the next node in the sequence. A singly linked list is a type of linked list where each node only has a reference to the next node in the sequence.
Here's a Java program that performs the following operations on a singly linked list:
1. Declare Node: Define a Node class with a value and a reference to the next node.
2. Add item in the Node: Create a new Node object and set its value, then set the next reference of the last node in the list to this new node.
3. Display the entire List: Traverse the list from the head node to the tail node, printing each node's value.
4. Add Item at Start: Create a new Node object and set its value, then set its next reference to the current head node and update the head node variable to point to the new node.
5. Add Item at End: Same as "Add item in the Node" above.
```
public class Node {
int value;
Node next;
public Node(int value) {
this.value = value;
this.next = null;
}
}
public class LinkedList {
Node head;
public LinkedList() {
this.head = null;
}
public void addItem(int value) {
Node newNode = new Node(value);
if (head == null) {
head = newNode;
} else {
Node current = head;
while (current.next != null) {
current = current.next;
}
current.next = newNode;
}
}
public void display() {
Node current = head;
while (current != null) {
System.out.print(current.value + " ");
current = current.next;
}
System.out.println();
}
public void addItemAtStart(int value) {
Node newNode = new Node(value);
newNode.next = head;
head = newNode;
}
public void addItemAtEnd(int value) {
addItem(value);
}
}
```
阅读全文