Insert in Cyclic Linked List
/***
Given
a node from a cyclic linked list which has been sorted, write a function to
insert a value into the
list
such that it remains a cyclic sorted list. The given node can be any single
node in the list.
Pay attention on edge case.
1. input is nullptr
2. duplicate and single node
***/
#include <iostream>
using namespace std;
struct node {
int val;
node *next;
node(int v) {
this->val = v;
this->next = nullptr;
}
};
void insert(node *&aNode, int x) {
if(aNode == nullptr) {
aNode = new node(x);
aNode->next = aNode;
return;
}
node *n = aNode;
while(true) {
if(n->val > n->next->val) { // n is tail and n->next is head
if(n->val < x || n->next->val > x) break;
else n = n->next;
} else if(n->val < n->next->val) { // n is mid node
if(n->val < x &&
n->next->val > x) break;
else n = n->next;
} else { // n is duplicate or itself
if(n == aNode) break;
else n = n->next;
}
}
node *k = new node(x);
node *t = n->next;
n->next = k;
k->next = t;
}
void main() {
node *head = new node(0);
// node *head = nullptr;
node *p, *a;
p = head;
// a = p;
for (int i = 0; i<1; i += 2)
{
//if
(i == 6) a = p;
node *n = new node(3);
p->next = n;
p = p->next;
}
head = head->next;
p->next = head;
insert(a, 5);
p = head;
do {
cout<<p->val;
p = p->next;
} while (p != head);
}
Comments
Post a Comment