-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCircularLinkedList.java
More file actions
101 lines (101 loc) · 3.09 KB
/
Copy pathCircularLinkedList.java
File metadata and controls
101 lines (101 loc) · 3.09 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
import java.util.Scanner;
public class CircularLinkedList {
class Node{
int data;
Node next;
Node(int data){
this.data=data;
this.next=null; }}
Node head=null;
Node tail=null;
public CircularLinkedList(){
this.head=null;
this.tail=null;
}
public void insert(int data){
Node newNode = new Node(data);
if (head == null) {
head = newNode;
tail = newNode;
tail.next = head;
return;
}
tail.next = newNode;
newNode.next = head;
tail = newNode;
}
public void display(){
if (head == null) {
System.out.println("List is empty");
return;
}
Node curr = head;
System.out.println("Circular Linked List: ");
do{
System.out.print(curr.data+" -> ");
curr = curr.next;
} while(curr!=head);
System.out.println("HEAD");
}
public void delete(int data){
Node node = head;
if (node == null) {
System.out.println("List is empty");
return;
}
if(head==tail && head.data==data){
head=null;
tail=null;
System.out.println("Deleted: "+data);
return;
}
if(node.data==data){
head=head.next;
tail.next=head;
System.out.println("Deleted: "+data);
return;
}
do {
Node next = node.next;
if (next.data == data) {
node.next = next.next;
if (next == tail) tail = node;
System.out.println("Deleted: " +data);
return;
}
node = node.next;
} while (node != head);
System.out.println("Value not found");
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
CircularLinkedList list = new CircularLinkedList();
int choice, val;
do {
System.out.println("\n1. Insert");
System.out.println("2. Delete");
System.out.println("3. Display");
System.out.println("4. Exit");
System.out.print("Enter choice: ");
choice = sc.nextInt();
switch (choice) {
case 1:
System.out.print("Enter value: ");
val = sc.nextInt();
list.insert(val);
break;
case 2:
System.out.print("Enter value to delete: ");
val = sc.nextInt();
list.delete(val);
break;
case 3:
list.display();
break;
case 4:
System.out.println("Exiting...");
break;
default:
System.out.println("Invalid choice");
}
} while (choice != 4); }}