-
Notifications
You must be signed in to change notification settings - Fork 1
/
LinkedList.java
100 lines (79 loc) · 1.83 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
package collection;
public class LinkedList<T> {
private Node<T> head;
private Node<T> tail;
public LinkedList() {
head = null;
tail = null;
}
public void add(T data) {
Node<T> node = new Node<T>(data, null, null);
Node<T> current=null;
if (head == null && tail == null) {
head = node;
tail = node;
head.setPrevious(null);
head.setNext(null);
tail.setNext(null);
tail.setPrevious(null);
} else {
tail=node;
current=head;
while(current.getNext()!=null) {
current=current.getNext();
}
current.setNext(tail);
tail.setPrevious(current);
}
}
public String toString() {
StringBuffer toReturn = new StringBuffer("[");
Node<T> curr = head;
while (curr!=null) {
toReturn.append(curr.getData()).append(" , ");
curr=curr.getNext();
}
toReturn.append("]");
return toReturn.toString();
}
private class Node<T> {
private T data;
private Node<T> previous;
private Node<T> next;
public Node(T data, Node<T> previous, Node<T> next) {
super();
this.data = data;
this.previous = previous;
this.next = next;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
public Node<T> getPrevious() {
return previous;
}
public void setPrevious(Node<T> previous) {
this.previous = previous;
}
public Node<T> getNext() {
return next;
}
public void setNext(Node<T> next) {
this.next = next;
}
}
public static void main(String[] args) {
LinkedList<String> list=new LinkedList<>();
System.out.println(list);
list.add("Hello");
list.add("ajay");
list.add("jay");
list.add("vijay");
list.add("Sanjay");
System.out.println("========================");
System.out.println(list);
}
}