#include<iostream>
#include<stdlib.h>
using namespace std;
#define error -1
/*
create and operate a list with a head node.
*/
typedef struct Lnode
{
int data;
Lnode *next;
} Lnode;
void listInsertIntoTail(Lnode *&h,Lnode *&r,int data);
void listInit(Lnode *&h,Lnode *&r)
{
h->next=h;
r=h;
}
void listCreateByTail(Lnode *&h,Lnode *&r)//create a list by inserting into the tail always
{
Lnode *newnode=(Lnode*)malloc(sizeof(Lnode));
newnode->data=0;
newnode->next=NULL;
h->next=newnode;
r=h->next;
r->next=h;
for(int i=1; i<6; i++)
{
listInsertIntoTail(h,r,i);
}
}
void listInsertIntoTail(Lnode *&h,Lnode *&r,int x)//insert x into list
{
Lnode *newnode=(Lnode*)malloc(sizeof(Lnode));
newnode->data=x;
newnode->next=NULL;
r->next=newnode;
r=r->next;
r->next=h;
newnode=NULL;
}
void deleteElem(Lnode *&h,int x)//delete the Element whose data equals x
{
Lnode *temp1,*temp2;
temp1=h;
while(temp1->next->data!=x)//to find whose next node's data is x
{
temp1=temp1->next;
if(temp1->next==h)//now, temp1 is the last node,it should break or it leads to error.
{
break;
}
}
if(temp1->next->data==x)
{
temp2=temp1->next;//to record the one needs to be deleted
temp1->next=temp1->next->next;//adjust the list
free(temp2);//delete node x
}
else
{
cout<<x<<" node dose not exist."<<endl;
}
temp1=NULL;
temp2=NULL;
}
void listUpdate(Lnode *&h,int oldvlue,int newvalue)//replace old with new
{
Lnode *temp=h;
while(temp!=NULL)
{
if(temp->data==oldvlue)
{
temp->data=newvalue;
}
temp=temp->next;
if(temp==h)
{
break;
}
}
temp=NULL;
}
int findElem(Lnode *h,int x)//return x's position
{
Lnode *temp=h;
int position=0;
while(temp->data!=x)
{
if(temp->next==h)
{
break;
}
temp=temp->next;
position++;
}
if(temp->data==x)
{
return position;
}
else
{
return error;
}
temp=NULL;
}
void listDestroy(Lnode *&h,Lnode *&r)//release all space
{
while(h->next!=h)
{
free(h);
h=h->next;
r->next=h;
}
free(r);
cout<<"List is destroyed."<<endl;
}
void printstate(Lnode *&h)
{
Lnode *temp=h->next;
while(temp!=h)
{
cout<<temp->data<<" ";
temp=temp->next;
}
cout<<endl;
temp=NULL;
}
int main()
{
Lnode *h=(Lnode*)malloc(sizeof(Lnode));
Lnode *r=h;
listInit(h,r);
//listCreateByHead(h);
cout<<"链表创建"<<endl;
listCreateByTail(h,r);
printstate(h);
cout<<"删除元素"<<endl;
deleteElem(h,0);
printstate(h);
cout<<"更新元素"<<endl;
listUpdate(h,2,-1);
printstate(h);
cout<<"查找元素"<<endl;
cout<<findElem(h,-1)<<endl;
cout<<"销毁链表"<<endl;
listDestroy(h,r);
h=NULL;
r=NULL;
return 0;
}