We have discussed the various concepts including the operations of Linked List in our previous post. So if you are unaware of these concepts, please visit our previous tutorials
Lets look at the complete Linked List creation in Java with all the operations we have discussed.
Here is the Java Code.
Lets look at the complete Linked List creation in Java with all the operations we have discussed.
Here is the Java Code.
import org.omg.Messaging.SyncScopeHelper;
public class LinkedList {
static LinkedNode head = null;
public static void main(String[] args) {
LinkedList linkedList = new LinkedList();
LinkedNode node = new LinkedNode(1);
linkedList.addNode(node);
LinkedNode node2 = new LinkedNode(2);
linkedList.addNode(node2);
LinkedNode node3 = new LinkedNode(3);
linkedList.addNode(node3);
System.out.println("After adding nodes, the list is -");
linkedList.printList();
int search = linkedList.searchNode(node3);
System.out.println("Node 3 found in index " + search);
linkedList.deleteNode(new LinkedNode(2));
System.out.println("After deleting node 2 if present, the list is -");
linkedList.printList();
}
private void deleteNode(LinkedNode node2) {
if(head == null){
System.out.println("List is empty");
return;
}
if(head.value == node2.value){
head = head.next;
return;
}else{
LinkedNode temp1 = head;
LinkedNode temp = head.next;
while(temp != null && temp.value != node2.value ){
temp1 = temp;
temp = temp.next;
}
if(temp == null){
System.out.println("The node to be delete is not found ");
}else{
temp1.next = temp.next;
}
}
}
private void printList() {
if(head != null){
LinkedNode temp = head;
while(temp != null){
System.out.print(temp.value + " ");
temp = temp.next;
}
System.out.println();
}else{
System.out.println("The List is empty, Please add node elements first");
}
}
private int searchNode(LinkedNode node2) {
int position = 0;
if(head == null){
System.out.println("List is empty");
return -1;
}
if(head.value == node2.value){
System.out.println("Node found a position " + position);
return -1;
}else{
LinkedNode temp = head;
while(temp != null && temp.value != node2.value ){
position++;
temp = temp.next;
}
if(temp == null){
System.out.println("Node found a position " + position);
return -1;
}
}
return position;
}
private void addNode(LinkedNode node) {
if(head == null){
head = node;
return;
}
else{
LinkedNode temp = head;
while(temp.next != null){
temp = temp.next;
}
temp.next = node;
}
}
}
class LinkedNode {
protected int value;
protected LinkedNode next;
public LinkedNode(int value) {
this.value = value;
this.next = null;
}
}
//output
//After adding nodes, the list is -
//1 2 3
//Node 3 found in index 2
//After deleting node 2 if present, the list is -
//1 3
That's all for Single Linked List. We will discuss about double linked list and circular linked list as part of our next tutorials. We will also discuss various interview questions related to these concepts.Hope you like it. Please comment on any doubts.
Happy Learning !!!
0 comments :
Post a Comment