-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathsingleLinkedList.java
135 lines (134 loc) · 3.05 KB
/
singleLinkedList.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
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
public class singleLinkedList
{
private node head; //storing head node
private int size;
//this is our main clss where we write methods for the list
//getters
public node getHead()
{
return head;
}
//setters
public void setHead(node h)
{
this.head = h;
}
//add to front method
public void addToFront(sample obj)
{
node n = new node(obj); //creating node
n.setNext(head);
head = n;
size++;
}
//printing the list
public void printList()
{
node current = head;
while(current!=null)
{
System.out.print(current+" -> ");
current = current.getNext();
}
System.out.println("null");
System.out.println("^");
System.out.println("HEAD");
}
//return the size of the list
public int getSize()
{
return size;
}
//check if list is empty or not
public boolean isEmpty()
{
if(head == null)
{
return true;
}
return false;
}
//remove the node from the front
public node removeFromFront()
{
if(isEmpty())
{
return null;
}
node removeNode = head;
head = head.getNext();
size--;
removeNode.setNext(null);
return removeNode;
}
//add to last
public void addToLast(sample obj)
{
node NewNode = new node(obj);
node current = head;
while(current.getNext() != null)
{
current = current.getNext();
}
size++;
current.setNext(NewNode);
}
//remove from the last
public node removeFromLast()
{
node current = head;
while(current.getNext().getNext() != null)
{
current = current.getNext();
}
node removeNode = current.getNext();
size--;
current.setNext(null);
return removeNode;
}
//remove the first finded specific node
public node removeFirst(sample obj)
{
node current = head;
node old=current;
while(current != null)
{
if(obj.equals(head.getSample()))
{
removeFromFront();
break;
}
else if(obj.equals(current.getSample()))
{
System.out.println("sucess");
old.setNext(current.getNext());
size--;
break;
}
old = current;
current = current.getNext();
}
return current;
}
//method for searching in the list
public boolean search(sample obj)
{
node NewNode = new node(obj);
node current = head;
int flag=0;
while(current != null)
{
if(NewNode.equal(current))
{
flag=1;
break;
}
current = current.getNext();
}
if(flag==1)
{
return true;
}
return false;
}
}