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-02-18 17:05:09 浏览: 91
Linked List is a data structure that consists of a sequence of nodes, where each node contains a piece of data and a reference to the next node in the sequence.
Single Linked List is a type of linked list where each node only has a reference to the next node in the sequence, and the sequence can only be traversed in one direction.
Here is the Java program to perform the operations you requested:
```java
public class LinkedListExample {
// Define a Node class
static class Node {
int data;
Node next;
public Node(int data) {
this.data = data;
this.next = null;
}
}
Node head; // head of the linked list
// Method to add a new node to the end of the linked list
public void add(int data) {
Node newNode = new Node(data);
if (head == null) {
head = newNode;
return;
}
Node last = head;
while (last.next != null) {
last = last.next;
}
last.next = newNode;
}
// Method to add a new node to the start of the linked list
public void addFirst(int data) {
Node newNode = new Node(data);
newNode.next = head;
head = newNode;
}
// Method to display the entire linked list
public void display() {
Node current = head;
while (current != null) {
System.out.print(current.data + " ");
current = current.next;
}
System.out.println();
}
public static void main(String[] args) {
LinkedListExample list = new LinkedListExample();
// Add elements to the end of the linked list
list.add(1);
list.add(2);
list.add(3);
// Display the entire linked list
list.display(); // Output: 1 2 3
// Add an element to the start of the linked list
list.addFirst(0);
// Display the entire linked list again
list.display(); // Output: 0 1 2 3
}
}
```
阅读全文