-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLinkedList.java
More file actions
93 lines (92 loc) · 1.71 KB
/
LinkedList.java
File metadata and controls
93 lines (92 loc) · 1.71 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
public class Main {
public static void main(String[] args) {
LinkedList li = new LinkedList();
li.insert("Faster AI&ML");
li.insert("Faster saas platforms");
li.insert("Tata");
li.insertAtPos(2, "Faster AI");
li.insertAtPos(4, "wipro");
li.deleteAt(4);
System.out.println(li.length());
li.show();
}
}
class Node {
String data;
Node next;
public Node(String data) {
this.data = data;
this.next = null;
}
}
class LinkedList {
Node head;
public LinkedList() {
this.head = null;
}
public boolean insert(String data) {
if (head == null) {
head = new Node(data);
return true;
} else {
Node temp = this.head;
while (temp.next != null) {
temp = temp.next;
}
temp.next = new Node(data);
return true;
}
}
public boolean insertAtPos(int pos, String data) {
Node newNode = new Node(data);
if (pos == 1) {
newNode.next = head;
head = newNode;
return true;
} else {
Node temp = head;
for (int i = 1; temp != null && i < pos - 1; i++) {
temp = temp.next;
}
newNode.next = temp.next;
temp.next = newNode;
return true;
}
}
public boolean deleteAt(int pos) {
if (head == null) {
return false;
}
if (pos == 1) {
head = head.next;
return true;
} else {
Node temp = head;
for (int i = 1; temp != null && i < pos - 1; i++) {
temp = temp.next;
}
temp.next = temp.next.next;
return true;
}
}
public int length() {
if (head == null) {
return 0;
}
int len = 0;
Node temp = head;
while (temp != null) {
len += 1;
temp = temp.next;
}
return len;
}
public void show() {
Node temp = this.head;
while (temp != null) {
System.out.println(temp.data);
// System.out.println();
temp = temp.next;
}
}
}