-
Notifications
You must be signed in to change notification settings - Fork 0
/
SinglyLinkedList.java
113 lines (110 loc) · 3.27 KB
/
SinglyLinkedList.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
package com.TrX;
public class SinglyLinkedList {
public Node Head;
public Node Tail;
public int size;
public Node CreateSinglyLinkedList(int nodeValue){
Node node = new Node();
node.next = null;
node.value = nodeValue;
Head = node;
Tail = node;
size = 1;
return Head;
}
//Insertion method in Linked List
public void InsertInLinkedList(int nodeValue , int location){
Node node = new Node();
node.value = nodeValue;
if(Head == null){
CreateSinglyLinkedList(nodeValue);
return;
} else if (location == 0) { //insertion in beginning
node.next = Head;
Head = node;
} else if (location >= size) { //insertion at the end
node.next = null;
Tail.next = node;
Tail = node;
} else { //insertion after Specified node
Node TempNode = Head;
int i = 0;
while(i < location-1){
TempNode = TempNode.next;
i++;
}
Node nextNode = TempNode.next;
TempNode.next = node;
node.next = nextNode;
}
size++;
}
//Traverse Singly Linked List
public void Traverse(){
if(Head == null){
System.out.println("LinkedList does not Exists!");
}
Node tempNode = Head;
for(int i = 0 ;i<size;i++){
System.out.print(tempNode.value);
if(i!=size-1){
System.out.print("->");
}
tempNode = tempNode.next;
}
System.out.println("\n");
}
//Searching in Linked List
public boolean Search(int nodeValue){
if(Head!=null){
Node tempNode = Head;
for(int i =0 ; i<size ; i++){
if(tempNode.value == nodeValue){
System.out.println("Found the node at location :"+i+"\n");
return true;
}
tempNode = tempNode.next;
}
}
System.out.println("Node not Found!");
return false;
}
//Deleting a node from Linked list
public void Delete(int location){
if(Head == null ){
System.out.println("Single Linked List does not exits!");
return;
} else if (location == 0) { //Deleting First node
Head = Head.next;
size--;
if(size==0){
Tail = null;
}
} else if (location>=size) { //Deleting the last node
Node tempNode = Head;
for(int i=0;i<size-1;i++){
tempNode = tempNode.next;
}
if(tempNode == Head){
Head = Tail = null;
size--;
return;
}
tempNode.next=null;
Tail = tempNode;
size--;
} //Deleting a specific Node
Node tempNode = Head;
for(int i=0;i<location-1;i++){
tempNode = tempNode.next;
}
tempNode.next = tempNode.next.next;
size--;
}
//Delete entire Linked List
public void DeleteLinkedList(){
Head = null;
Tail = null;
System.out.println("The LinkedList Has Been deleted");
}
}