-
Notifications
You must be signed in to change notification settings - Fork 206
Expand file tree
/
Copy pathSinglyLinkedList.java
More file actions
94 lines (85 loc) · 2.55 KB
/
SinglyLinkedList.java
File metadata and controls
94 lines (85 loc) · 2.55 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
import java.util.*;
class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String ch = "";
LinkedList list = new LinkedList();
do {
System.out.println("Enter the value");
int n = sc.nextInt();
sc.nextLine();
list.addNode(n);
System.out.println("Do you want to add another node? Type Yes/No");
ch = sc.nextLine();
} while (ch.equals("Yes"));
System.out.println("Enter the element to be deleted");
int d = sc.nextInt();
list.delete(d);
System.out.print("The elements in the linked list are ");
list.display();
System.out.println();
System.out.println("Total number of elements present in list are " + list.count());
}
static class Node {
int data;
Node next;
public Node(int data) {
this.data = data;
this.next = null;
}
}
static class LinkedList {
Node head, next, temp, pre;
public LinkedList() {
head = null;
}
public void addNode(int data) {
Node newnode = new Node(data);
if (head == null) {
head = newnode;
} else {
temp = head;
while (temp.next != null) {
temp = temp.next;
}
temp.next = newnode;
}
}
public int count() {
temp = head;
int count = 0;
while (temp != null) {
count++;
temp = temp.next;
}
return count;
}
public void delete(int element) {
temp = head;
int k = 0;
if (head.data == element) {
head = head.next;
}
while (temp.next != null) {
if (temp.next.data == element) {
k = 1;
temp.next = temp.next.next;
} else {
pre = temp.next;
temp = temp.next;
}
}
if (k == 1)
System.out.println(element + " is deleted from the list");
else
System.out.println(element + " is not present in the list");
}
public void display() {
temp = head;
while (temp != null) {
System.out.print(temp.data + " ");
temp = temp.next;
}
}
}
}