-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcircularlinkedlistinsertionandtrversal.cpp
More file actions
130 lines (104 loc) · 2.57 KB
/
circularlinkedlistinsertionandtrversal.cpp
File metadata and controls
130 lines (104 loc) · 2.57 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
120
121
122
123
124
125
126
127
128
129
#include <iostream>
struct Node
{
int data;
Node *next;
};
void linkedListTraversal(Node *head)
{
Node *ptr = head;
do
{
std::cout << "Element is " << ptr->data << std::endl;
ptr = ptr->next;
} while (ptr != head);
}
Node *insertAtFirst(Node *head, int data)
{
Node *ptr = new Node();
ptr->data = data;
Node *p = head->next;
while (p->next != head)
{
p = p->next;
}
// At this point p points to the last node of this circular linked list
p->next = ptr;
ptr->next = head;
head = ptr;
return head;
}
int main()
{
Node *head = NULL;
Node *second = NULL;
Node *third = NULL;
Node *fourth = NULL;
// Allocate memory for nodes in the linked list in Heap
head = new Node();
second = new Node();
third = new Node();
fourth = new Node();
// Link first and second nodes
head->data = 4;
head->next = second;
// Link second and third nodes
second->data = 3;
second->next = third;
// Link third and fourth nodes
third->data = 6;
third->next = fourth;
// Terminate the list at the third node
fourth->data = 1;
fourth->next = head;
std::cout << "Circular linked list before insertion" << std::endl;
linkedListTraversal(head);
head = insertAtFirst(head, 8);
std::cout << "Circular linked list after insertion" << std::endl;
linkedListTraversal(head);
return 0;
}
//java
class Node {
int data;
Node next;
}
public class Main {
public static void linkedListTraversal(Node head) {
Node ptr = head;
do {
System.out.println("Element is " + ptr.data);
ptr = ptr.next;
} while (ptr != head);
}
public static Node insertAtFirst(Node head, int data) {
Node ptr = new Node();
ptr.data = data;
Node p = head.next;
while (p.next != head) {
p = p.next;
}
p.next = ptr;
ptr.next = head;
head = ptr;
return head;
}
public static void main(String[] args) {
Node head = new Node();
Node second = new Node();
Node third = new Node();
Node fourth = new Node();
// Link first and second nodes
head.data = 4;
head.next = second;
// Link second and third nodes
second.data = 3;
second.next = third;
// Link third and fourth nodes
third.data = 6;
third.next = fourth;
// Terminate the list at the third node
fourth.data = 1;
fourth.next = head;
}
}