-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathLinkedList.java
More file actions
130 lines (116 loc) · 2.83 KB
/
Copy pathLinkedList.java
File metadata and controls
130 lines (116 loc) · 2.83 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
public class LinkedList {
private Node head;
private Node tail;
private int size;
class Node{
private int data;
private Node next;
public Node(int data){
this.data = data;
this.next = null;
}
public String toString(){
return String.valueOf(this.data);
}
}
public void addFirst(int data){
Node newNode = new Node(data);
newNode.next = head;
head = newNode;
size++;
if(head.next == null)
tail = head;
}
public void addLast(int data){
if(size == 0){
addFirst(data);
}
else {
Node newNode = new Node(data);
tail.next = newNode;
tail = newNode;
size++;
}
}
public void add(int k, int data){
if(k == 0){
addFirst(data);
}else{
Node temp1 = node(k-1);
Node temp2 = temp1.next;
Node newNode = new Node(data);
temp1.next = newNode;
newNode.next = temp2;
size++;
if(newNode.next == null)
tail = newNode;
}
}
public Node node(int idx){
Node x = head;
for(int i = 0; i< idx; i++)
x = x.next;
return x;
}
public String toString(){
if(head == null){
return "[]";
}
Node temp = head;
String str = "[";
while (temp.next != null) {
str += temp.data + ", ";
temp = temp.next;
}
str += temp.data;
return str+"]";
}
public int removeFirst(){
Node temp = head;
head = head.next;
int returnData = temp.data;
temp = null;
size--;
return returnData;
}
public int remove(int k){
if(k == 0)
return removeFirst();
Node temp = node(k-1);
Node todoDeleted = temp.next;
temp.next = temp.next.next;
int returnData = todoDeleted.data;
if(todoDeleted == tail)
tail = temp;
todoDeleted = null;
size--;
return returnData;
}
public int removeLast(){
return remove(size-1);
}
public int getSize(){
return size;
}
public int getElement(int k){
Node temp = node(k);
return temp.data;
}
// Output
// [30, 10, 20]
// 10
// [30, 20]
// 2
//20
public static void main(String[] args) {
LinkedList list = new LinkedList();
list.addLast(10);
list.addLast(20);
list.addFirst(30);
System.out.println(list);
System.out.println(list.remove(1));
System.out.println(list);
System.out.println(list.getSize());
System.out.println(list.getElement(1));
}
}