-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLinkedList.java
More file actions
148 lines (116 loc) · 2.43 KB
/
LinkedList.java
File metadata and controls
148 lines (116 loc) · 2.43 KB
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
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
class Node {
Node next;
Object data;
Node(Object dataValue){
next=null;
data=dataValue;
}
Node(Object dataValue,Node nextValue){
next=nextValue;
data=dataValue;
}
Object getData(){
return data;
}
void setData(Object dataValue){
data=dataValue;
}
Node getNext(){
return next;
}
public void setNext(Node nextValue){
next=nextValue;
}
}
class LinkedListDS{
int counter=0;
Node head;
LinkedListDS(){
head=new Node(null);
}
void add(Object data){
Node temp = new Node(data);
Node current = head;
while(current.getNext() != null){
current = current.getNext();
}
current.setNext(temp);
counter++;
}
void add(Object data, int index){
Node temp=new Node(data);
Node current = head;
if (index > counter+1){
System.out.println("Index cannot be greater than length");
}
else{
int tempCount=0;
while (tempCount != index && tempCount<=counter){
current=current.getNext();
tempCount++;
}
temp.setNext(current.getNext());
current.setNext(temp);
counter++;
}
}
boolean deleteElement(Object data){
Node current = head;
Node prev = head;
while( current.getNext() != null ){
if (current.getData() == data){
prev.setNext(current.getNext());
counter--;
return true;
}
else{
prev=current;
current=current.getNext();
}
}
return false;
}
Object getValue(int index){
int tempCount=0;
Node current = head;
while(tempCount<=counter && current.getNext() != null){
if (tempCount==index){
return current.getNext().getData();
}
else{
current=current.getNext();
tempCount++;
}
}
return null;
}
void display(){
Node current = head.getNext();
while(current != null){
System.out.println( "Current Addr=" + current + " " +
"Next Addr=" + current.getNext() + " " +
current.getData());
current=current.getNext();
}
}
int getSize(){
return counter;
}
}
public class LinkedList {
public static void main(String args[]){
LinkedListDS ll=new LinkedListDS();
ll.add(5);
ll.add(10);
ll.add(15);
ll.add(1,0);
ll.add(2,10);
ll.display();
System.out.println("LinkedList Size="+ll.getSize());
System.out.println(ll.deleteElement(5));
System.out.println(ll.deleteElement(5));
ll.display();
System.out.println("LinkedList Size="+ll.getSize()+" " +ll.head.getNext());
System.out.println(ll.getValue(0));
}
}