-
Notifications
You must be signed in to change notification settings - Fork 0
/
LinkedList.java
131 lines (119 loc) · 3.13 KB
/
LinkedList.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
package data.structures.LinkedList;
/**
*
* @author jasleen
* @param <T>
*/
public class LinkedList <T>{
Node<T> head=null;
private Node<T> current;
public void remove(T t)
{
//System.out.println(t);
Node currentTraversing=head();
if(currentTraversing.key()==t)
{
if(current==currentTraversing)
current=null;
head(currentTraversing.next());
currentTraversing=null;
return;
}
while(currentTraversing.next()!=null &&!currentTraversing.next().key().equals(t))
{
currentTraversing=currentTraversing.next();
}
if(currentTraversing!=null)
{
Node itemToBeremoved=currentTraversing.next();
if(itemToBeremoved==null)
{
System.out.println("Key not found. Sorry!!!");
}
if(itemToBeremoved==current)
current=currentTraversing;
if(itemToBeremoved!=null&&itemToBeremoved.next()!=null)
currentTraversing.next(itemToBeremoved.next());
else
currentTraversing.next(null);
}
}
public void remove()
{
Node currentTraversing=head();
if(currentTraversing!=null)
{
while(currentTraversing!=null&& currentTraversing.next()!=current)
{
currentTraversing=currentTraversing.next();
}
System.out.println(currentTraversing.key());
currentTraversing.next(null);
current=currentTraversing;
}
else
{
System.out.println("No Item to remove");
}
}
public void setCurrent(Node<T> current) {
this.current = current;
}
public void add(T t)
{
if(head()!=null)
{
current.next(new Node<>(t));
current=current.next();
}
else
{
head=new Node<>(t);
current=head;
}
}
public void addAtHead(T t)
{
if(head()!=null)
{
Node oldHead=head();
//Setting head to new node
Node newHead=new Node<>(t);
head(newHead);
//Setting the next element of new head to old head
head().next(oldHead);
}
else
{
head=new Node<>(t);
}
}
public Node<T> head()
{
return head;
}
public void head(Node<T> t)
{
this.head=t;
}
@Override
public String toString() {
StringBuilder builder=new StringBuilder();
builder.append("[");
builder.append("\t");
Node currentTraversing=head();
while(currentTraversing!=null)
{
builder.append(currentTraversing.key().toString());
builder.append("\t");
currentTraversing=currentTraversing.next();
}
builder.append("]");
return builder.toString();
}
public void removeHead() {
Node oldHead=head();
head(oldHead.next());
oldHead=null;
}
}