-
Notifications
You must be signed in to change notification settings - Fork 111
Expand file tree
/
Copy pathLinkedListApp.java
More file actions
119 lines (102 loc) · 2.16 KB
/
Copy pathLinkedListApp.java
File metadata and controls
119 lines (102 loc) · 2.16 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
public class LinkedListApp {
public static void main(String[] args) {
// TODO code application logic here
LinkList x = new LinkList();
x.insertFirst(5);
x.insertFirst(6);
x.displayList();
//x.insertFirst(10);
// x.insertFirst(20);
// x.displayList();
// x.deleteFirst();
x.delete(2);
//Node k = x.find(2);
// k.displayNode();
x.displayList();
}
}
class Node {
int data;
Node next;
Node(int item) { //constructor
this.data = item;
this.next = null;
}
void displayNode() {
System.out.print(this.data + " ");
}
}
class LinkList {
private Node head;
public LinkList() { //constructor
head = null;
}
public boolean isEmpty() {
return (this.head == null);
}
public void insertFirst(int i) {
Node newNode = new Node(i);
newNode.next = head;
head = newNode;
//System.out.println(head);
}
public Node deleteFirst() {
if (isEmpty()) {
System.out.println("List is empty,nothing to delete");
return null;
}
Node temp = head;
head = head.next; //head move to second object
temp.next = null; // break the link,security problem
//because we return temp its next have link with other object
return temp;
}
public void displayList() {
if (isEmpty()) {
System.out.println("List is empty, Nothing to display");
}
Node current = head;
while (current != null) {
current.displayNode();
current = current.next;
}
System.out.println();
}
public Node find(int key) {
Node current = head;
int count = 1;
while (current != null) {
if (count == key) {
return current;
}
current = current.next;
count++;
}
System.out.println("Item not found");
return null;
}
public void delete(int key) {
if (isEmpty()) {
System.out.println("List is em[ty. Nothing to delete");
return;
}
Node current = head;
Node previous = head;
int count = 1;
while (current != null) {
if (count == key) {
if (count == 1) {
head = head.next;
} else {
previous.next = current.next;
}
System.out.println("Item deleted");
return;
}
previous = current;
current = current.next;
count++;
}
System.out.println("Item not available. Deletion terminated");
}
}