-
Notifications
You must be signed in to change notification settings - Fork 0
/
task5.cpp
142 lines (130 loc) · 2.55 KB
/
task5.cpp
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
130
131
132
133
134
135
136
137
138
139
140
141
142
// Will be implementing Singly Circular Linked List as Doubly haven't discussed yet in lectures
#include <iostream>
using namespace std;
class Node
{
// private:
int Data;
Node *Next;
public:
// default constructor
Node();
// setters
void setData(int);
void setNext(Node *);
// getters
int getData();
Node *getNext();
};
// Function Implementattion for class Node
// default constructor
Node ::Node()
{
Data = 0;
Next = NULL;
}
// setters
void Node ::setData(int x)
{
Data = x;
}
void Node ::setNext(Node *next)
{
Next = next;
}
// getters
int Node ::getData()
{
return Data;
}
Node *Node ::getNext()
{
return Next;
}
class CircularLinkedList
{
public:
Node *Head;
// default constructor
CircularLinkedList();
// fucntions
void InsertAtFirst(int);
void InsertAtLast(int);
void MakeCircular();
void Display();
};
// Function Implementattion for class CircularLinkedList
// default constructor
CircularLinkedList ::CircularLinkedList()
{
Head = NULL;
}
void CircularLinkedList ::InsertAtLast(int x)
{
Node *newnode = new Node;
newnode->setData(x);
if (Head == NULL)
{
Head = newnode;
}
else
{
Node *temp = Head;
while (temp->getNext() != NULL)
{
temp = temp->getNext();
}
temp->setNext(newnode);
}
}
void CircularLinkedList ::MakeCircular()
{
// for making circular linked list
Node *temp = Head;
while (temp->getNext() != NULL)
{
temp = temp->getNext();
}
temp->setNext(Head);
}
void CircularLinkedList ::Display()
{
Node *temp = Head;
cout << "Linked List: ";
while (temp->getNext() != Head)
{
cout << temp->getData() << " ";
temp = temp->getNext();
}
cout << temp->getData() << " ";
}
// function for returning value of middle node
int MiddleVal(Node *head)
{
Node *temp = head;
int cnt = 0;
while (temp != NULL)
{
temp = temp->getNext();
cnt++;
}
// middle node for odd number of nodes
cnt = cnt / 2 + 1;
Node *temp1 = head;
for (int i = 1; i < cnt; i++)
{
temp1 = temp1->getNext();
}
return temp1->getData();
}
int main()
{
CircularLinkedList l1;
l1.InsertAtLast(1);
l1.InsertAtLast(2);
l1.InsertAtLast(3);
l1.InsertAtLast(4);
l1.InsertAtLast(5);
cout << MiddleVal(l1.Head);
return 0;
}