-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path19_CircularLinkedList.java
More file actions
56 lines (50 loc) · 1.34 KB
/
19_CircularLinkedList.java
File metadata and controls
56 lines (50 loc) · 1.34 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
import java.util.Scanner;
class CNode {
int data;
CNode next;
CNode(int data) {
this.data = data;
this.next = null;
}
}
public class CircularLinkedList {
CNode head = null;
CNode tail = null;
void insert(int data) {
CNode newNode = new CNode(data);
if (head == null) {
head = newNode;
tail = newNode;
tail.next = head;
} else {
tail.next = newNode;
tail = newNode;
tail.next = head;
}
}
void display() {
if (head == null) {
System.out.println("List is empty.");
return;
}
CNode temp = head;
System.out.print("Circular Linked List: ");
do {
System.out.print(temp.data + " -> ");
temp = temp.next;
} while (temp != head);
System.out.println("(Back to Head)");
}
public static void main(String[] args) {
CircularLinkedList list = new CircularLinkedList();
Scanner sc = new Scanner(System.in);
System.out.print("Enter number of nodes: ");
int n = sc.nextInt();
for (int i = 0; i < n; i++) {
System.out.print("Enter data for node " + (i + 1) + ": ");
list.insert(sc.nextInt());
}
list.display();
sc.close();
}
}