-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCircularLinkedList2.java
More file actions
110 lines (109 loc) · 1.95 KB
/
CircularLinkedList2.java
File metadata and controls
110 lines (109 loc) · 1.95 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
public class CircularLinkedList2 {
class Node{
int data;
Node next;
Node(int data){
this.data=data;
this.next=null;
}
}
Node head=null;
Node tail=null;
void addNode(int data) {
Node n=new Node(data);
if(head==null) {
head=n;
tail=n;
n.next=head;
}
tail.next=n;
tail=n;
tail.next=head;
}
void deleteAtbeg() {
if(head==null) {
System.out.println("List is Empty");
return;
}
else if(head !=tail) {
head=head.next;
tail.next=head;
}
else {
head=tail=null;
}
}
void deleteAtend() {
if(head==null) {
System.out.println("List is Empty");
return;
}
else if(head !=tail) {
Node temp=head;
Node ptr=temp.next;
while(ptr.next !=head) {
temp=ptr;
ptr=ptr.next;
}
temp.next=head;
tail=temp;
}
else {
head=tail=null;
}
}
void deleteAtAnypos(int pos) {
if(head==null) {
System.out.println("List is Empty");
return;
}
else if(head !=tail) {
Node temp=head;
Node ptr=temp.next;
for(int i=0; i<pos-2; i++) {
temp=ptr;
ptr=ptr.next;
}
temp.next=ptr.next;
}
else {
head=tail=null;
}
}
void display() {
Node temp=head;
if(head==null) {
System.out.println("List is Empty");
return;
}
else {
do {
System.out.print(temp.data+",");
temp=temp.next;
}
while(temp !=head);
System.out.println();
}
}
public static void main(String[] args) {
CircularLinkedList2 c1=new CircularLinkedList2();
c1.addNode(10);
c1.addNode(20);
c1.addNode(30);
c1.addNode(40);
c1.addNode(50);
c1.addNode(60);
c1.addNode(70);
c1.addNode(80);
c1.display();
System.out.println("After Deleting the First Element From the Linked List");
c1.deleteAtbeg();
c1.display();
System.out.println("After Deleting the last Element From the Linked List");
c1.deleteAtend();
c1.display();
System.out.println("After Deleting the Element AtAnypostion From the Linked List");
c1.deleteAtAnypos(3);
c1.display();
}
}