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-15 22:03:23 浏览: 71
Java实现LinkedList
Linked-List is a data structure that consists of a sequence of nodes, each containing a reference to the next node in the sequence. It is a dynamic data structure, meaning that it can grow or shrink in size during the execution of a program.
Single Linked List is a type of Linked-List in which each node contains a reference to the next node in the sequence, but not to the previous node. This means that traversal of the list can only be done in one direction, from the first node to the last node.
Here is a Java program to perform the operations mentioned in the question:
```java
public class LinkedList {
Node head; // declaring head of the List
// Node class to create new nodes
static class Node {
int data;
Node next;
Node(int d) {
data = d;
next = null;
}
}
// method to add item in the List
public void addItem(int data) {
Node newNode = new Node(data);
// if List is empty, make newNode as head
if (head == null) {
head = newNode;
return;
}
// traverse to the end of the List
Node lastNode = head;
while (lastNode.next != null) {
lastNode = lastNode.next;
}
// add newNode at the end of the List
lastNode.next = newNode;
}
// method to display the entire List
public void displayList() {
Node currentNode = head;
// traverse the List and print data of each node
while (currentNode != null) {
System.out.print(currentNode.data + " ");
currentNode = currentNode.next;
}
System.out.println();
}
// method to add item at the start of the List
public void addItemAtStart(int data) {
Node newNode = new Node(data);
// make newNode as head of the List
newNode.next = head;
head = newNode;
}
// method to add item at the end of the List
public void addItemAtEnd(int data) {
addItem(data);
}
public static void main(String[] args) {
LinkedList list = new LinkedList();
// adding items to the List
list.addItem(10);
list.addItem(20);
list.addItem(30);
list.addItem(40);
// displaying the List
list.displayList();
// adding item at the start of the List
list.addItemAtStart(5);
list.displayList();
// adding item at the end of the List
list.addItemAtEnd(50);
list.displayList();
}
}
```
Output:
```
10 20 30 40
5 10 20 30 40
5 10 20 30 40 50
```
阅读全文