/*Circular linked list */
using ElementType = int;
struct Node{
ElementType data;
Node* next;
};
using PtrNode = Node*;
using Position = Node*;
//Operation .
void InitList(PtrNode p);
bool IsEmpty(PtrNode p);
void Insert(PtrNode p, ElementType value, Position pos);
void Delete(PtrNode p,ElementType value);
Position Find(PtrNode p, ElementType value);
Position FindPrevious(PtrNode p, ElementType value);
void ClearList(PtrNode p);
void PrintList(PtrNode p);
bool IsLast(PtrNode p, Position pos);
void CreateList(PtrNode p);
/*implemenation of circular linked list */
#include<iostream>
#include"circular_linked_list.h"
bool IsEmpty(PtrNode p){
return p->next == p;
}
void InitList(PtrNode p){
p->next = p;
std::cout << "Initialize successfully " << std::endl;
}
void Insert(PtrNode p, ElementType value, Position pos){
PtrNode new_node = new Node;
new_node->data = value;
new_node->next = pos->next;
pos->next = new_node;
}
bool IsLast(PtrNode p, Position pos){
if (!IsEmpty(p))
return pos->next == p;
return false;
}
void Delete(PtrNode p, ElementType value){
Position tmp=FindPrevious(p, value);
Position temp = Find(p, value);
if (!IsLast(p, tmp)){
tmp->next = temp->next;
delete temp;
}
}
Position Find(PtrNode p, ElementType value){
Position tmp = p->next;
while (tmp!= p&&tmp->data != value)
tmp = tmp->next;
if (tmp == p)
return nullptr;
return tmp;
}
Position FindPrevious(PtrNode p, ElementType value){
Position temp = p;
while (temp->next != p&&temp->next->data != value)
temp = temp->next;
if (temp->next == p)
return nullptr;
return temp;
}
void PrintList(PtrNode p){
Position temp = p->next;
while (temp != p){
std::cout << temp->data << " ";
temp = temp->next;
}
}
void ClearList(PtrNode p){
Position temp = p->next;
Position tmp;
while (temp != p){
tmp = temp->next;
delete temp;
temp = tmp;
}
p->next = p;
}
/*Create a list for the purpose of test*/
void CreateList(PtrNode p){
/*p is a head node */
/*create a circular list with ten nodes */
PtrNode new_node;
for (int i = 0; i < 10; ++i){
new_node = new Node;
new_node->data = rand() % 100 + 1;
new_node->next = p->next;
p->next = new_node;
}
}
int main(){
PtrNode p = new Node;
std::cout << "Call the InitList function \n";
InitList(p);
std::cout << "Create a list with ten nodes for test \n";
CreateList(p);
std::cout << "Print all the elements in the list :";
PrintList(p);
std::cout << "Insert a node after the head node \n";
Insert(p, 888, p);
std::cout << "Print all the elements in the list :";
PrintList(p);
std::cout << std::endl;
std::cout << "Delete 888 from the list \n";
Delete(p, 888);
std::cout << "Print all the elements in the list :";
PrintList(p);
}
原文:http://blog.csdn.net/u014343243/article/details/45130391