I tried to implement a linked list that can do pop(), push(), append(), printall(), and so on, and also I tried to handle the wraparound features, and de-wrap it when check if the list is cyclic to avoid endless loop, but I am sure this wrap and de-wrap features can be implemented better...
#include <iostream>
struct Node{
int value;
Node* next;
};
class LinkedList{
std::size_t count;
Node* head;
public:
void pop(); //pop from head
void push(int); //push from head
void append(int); //append at end
void wraparound(); //wrap around the list
bool isCyclicDwrap(); //check if cyclic, if yes, de-wrap-around it
void printll() const;
std::size_t size() const { return count; }
LinkedList(): head(nullptr),count(0) {}
~LinkedList();
};
void LinkedList::pop(){
if(head==nullptr){
std::cout<<"empty stack !"<<std::endl;
exit(0);
}
Node* cur = head;
Node* tmp = cur->next;
head = tmp;
delete cur; count--;
}
void LinkedList::append(int data){
Node* cur = head;
Node* tmp = new Node;
tmp->value = data;
tmp->next = nullptr;
if(!cur){
head = tmp; count++;
}
else{
while(cur->next != nullptr){
cur = cur->next;
}
cur->next = tmp; count++;
}
}
void LinkedList::wraparound(){
Node* cur =head;
while(cur->next != nullptr)
cur=cur->next;
cur->next = head;
}
bool LinkedList::isCyclicDwrap()
{
Node *n1, *n2;
n1 = head;
n2 = head->next;
do{
n1 = n1->next;
n2 = n2->next->next;
if(n1 == n2){
Node* cur =head;
size_t cnt=count;
while(--cnt != 0)
cur=cur->next; //move to the last node
cur->next=nullptr; // -> de-warp-around !
return true;
}
}while(n1 != head);
return false;
}
void LinkedList::push(int data)
{
Node* cur = (Node*)malloc(sizeof(Node));
cur->value=data;
cur->next=head;
count++;
head=cur;
}
void LinkedList::printll() const{
if(head==nullptr)
std::cout<<"empty Linkedlist!"<<std::endl;
Node* cur = head;
while(cur != nullptr){
std::cout << cur->value << '\n';
cur = cur->next;
}
}
LinkedList::~LinkedList()
{
Node* cur = head;
while (cur != NULL)
{
Node* next = cur->next;
delete cur;
cur = next;
}
head = NULL;
}
int main(){
LinkedList LL;
LL.append(5);
LL.append(6);
LL.append(7);
LL.printll();
std::cout<<"size of the stack/linkedlist: "<<LL.size()<<std::endl;
LL.wraparound();
std::cout<<"Cyclic: "<<LL.isCyclicDwrap()<<"; if 1, then remove the Cyclic feauture!"<<std::endl;
LL.push(4); //push
LL.printll();
std::cout<<"size of the stack/linkedlist: "<<LL.size()<<std::endl;
LL.pop();
LL.printll();
std::cout<<"size of the stack/linkedlist: "<<LL.size()<<std::endl;
LL.pop();
LL.printll();
std::cout<<"size of the stack/linkedlist: "<<LL.size()<<std::endl;
LL.pop();
LL.printll();
std::cout<<"size of the stack/linkedlist: "<<LL.size()<<std::endl;
LL.pop();
}