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-20 15:00:08 浏览: 55
Linked-List is a data structure that consists of a sequence of nodes, where each node contains a piece of data and a pointer to the next node in the sequence. A Single Linked List is a type of Linked List where each node has only one pointer to the next node in the sequence.
Here's a Java program that performs the following operations on a Single Linked List:
a) Declare Node:
```
class Node {
int data;
Node next;
}
```
b) Add item in the Node:
```
public static void addItem(Node head, int data) {
Node newNode = new Node();
newNode.data = data;
newNode.next = null;
if (head == null) {
head = newNode;
} else {
Node lastNode = head;
while (lastNode.next != null) {
lastNode = lastNode.next;
}
lastNode.next = newNode;
}
}
```
c) Display the entire List:
```
public static void displayList(Node head) {
Node currentNode = head;
if (currentNode == null) {
System.out.println("List is empty");
} else {
while (currentNode != null) {
System.out.print(currentNode.data + " ");
currentNode = currentNode.next;
}
System.out.println();
}
}
```
d) Add Item at Start:
```
public static Node addItemAtStart(Node head, int data) {
Node newNode = new Node();
newNode.data = data;
newNode.next = head;
head = newNode;
return head;
}
```
e) Add Item at End:
```
public static Node addItemAtEnd(Node head, int data) {
Node newNode = new Node();
newNode.data = data;
newNode.next = null;
if (head == null) {
head = newNode;
} else {
Node lastNode = head;
while (lastNode.next != null) {
lastNode = lastNode.next;
}
lastNode.next = newNode;
}
return head;
}
```
Note: These methods can be called from the main method to perform the operations on the Single Linked List.
阅读全文