Linked list is a linear data structure which stores data in nodes. Each node has a link to other node. A linked list has three different types listed as follows.
- · Singly Linked list
- · Doubly Linked list
- · Circular Linked list
Let us implement singly linked list in java.
Logic:
- First, create a node structure.
- It has a data element and link.
- Initialise the data and link in the constructor.
- Define two functions insert() and display().
- ‘insert()’ :
- Create an object for node.
- Check the head pointer is null then, assign the head to new node.
- Create a temp variable. If the temp.link is not null then make the ‘temp’ variable as temp.link.
- ‘display()’:
- Assign the ‘temp’ variable to head.
- ‘temp’ is not null, print the dull.
- ‘main()’ :
- Create a object for SinglyLinkedListEg.
- Call the insert() function to add the data.
- Call the display() function to display the data.
Program:
class SinglyLinkedListEg {
class Node {
int data;
Node link;
Node(int data)
{
this.data
= data;
this.link
= null;
}
}
Node head;
public void
insert(int data) {
Node newNode1
= new Node(data);
if (head ==
null) {
head =
newNode1;
} else {
Node temp
= head;
while
(temp.link != null) {
temp =
temp.link;
}
temp.link
= newNode1;
}
}
public void
display() {
Node temp =
head;
while (temp !=
null) {
System.out.print(temp.data + " -> ");
temp =
temp.link;
}
System.out.println("null");
}
public static
void main(String[] args) {
SinglyLinkedListEg s1 = new SinglyLinkedListEg();
// add data
elements to the linked list
s1.insert(110);
s1.insert(220);
s1.insert(300);
s1.insert(789);
s1.insert(456);
// Display the
list
System.out.println("Singly Linked List:");
s1.display();
}
}
Output:
Compile and run the program as follows….
C:\raji\blog>javac SinglyLinkedListEg.java
C:\raji\blog>java SinglyLinkedListEg
Singly Linked List:
110 -> 220 -> 300 -> 789 -> 456 -> null
Yes. This is the implementation of Singly Linked list in java.
Hope you understand this code. Keep coding!!!
No comments:
Post a Comment