您的位置:首页 > 编程语言 > C语言/C++

C++写的带有头结点单链表创建,插入,删除,显示

2012-08-21 09:07 381 查看
#include <iostream>

using namespace std;


struct link

{

char data;

struct link *next;

};


link *head,*tail;  //创建头指针和尾指针


int creat();

/******显示数据*************/

void show()

{

link *q=head;

if(head->next==NULL)

{

cout<<"无任何数据,请创建链表"<<endl;

creat();

}

else

{

q=q->next;     //跳过头结点

cout<<"show:";

do{

cout<<q->data<<"  ";

q=q->next;

}while(q!=NULL);

cout<<endl;

}

}


/*****带有头结点的创建,分为头插法和尾插法***************/

int creat()

{

char j;

int m=0;   //创建的节点数目

link *p,*q;

q=head;

if(q->next!=NULL)

{

cout<<"已经创建好数据链表"<<endl;

return -1;

}

else

{

int i;

cout<<"是插在头部还是尾部0:头部;1:尾部 :";

cin>>i;

cout<<"请输入,以#结束"<<endl;

if(i==1)

{

while(cin>>j,j!='#')

{

p=new link;        //生成新节点

p->data=j;

tail->next=p;     //把新节点加到以生成的节点的后面

tail=p;           //尾指针指向新生成的节点

m++;

}

tail->next=NULL;    //尾节点下一个指向为NULL

}

else

{

tail=NULL;     //尾指针为NULL

while(cin>>j,j!='#')

{

p=new link;        //生成新节点

p->data=j;

head->next=p;

p->next=tail;

tail=p;

if(m==0)

q=p;

m++;

}

q->next=NULL;  //尾节点下一个指向为NULL

}

return m;

}

}



/*********删除指定节点***********/

void delelte()

{

link *p=head->next;//P指向第一个节点,跳过头结点

link *q=head;

char m;

int n=0;

cout<<"请输入要删除的节点data: ";

cin>>m;

while(p!=NULL)

{

if(m==p->data)

{

q->next=p->next;

p=NULL;

n=1;

break;

}

else

{

p=p->next;

    q=q->next;

}

}

if(n==1)

cout<<"删除完成!"<<endl;

else

cout<<"不存在你要删除的!"<<endl;

show();

}


/*******插入一个节点************/

void insert()

{

link *p=head->next;

int m;

int n=0;

char data1;

cout<<"请问要插在哪里?0:表头;1:某个数后面 ";

cin>>m;

cout<<"请输入data ";

cin>>data1;

if(m==0)

{


link *q=new link;

q->data=data1;

head->next=q;

q->next=p;

}

else

{

char data2;

cout<<"请输入你要插哪个数后面,请输入它的data ";

cin>>data2;

    while(p!=NULL)

{

if(data2==p->data)

{   link *f=new link;

p->next=f;

f->next=p->next;

    n=1;

    break;

}

else

{

    p=p->next;

}

}

if(n==0)

cout<<"不存在你要插的这个数";

}

show();

}



int main()

{

head=new link;

head->next=NULL;

tail=head;    //尾指针指向头结点

int i=creat();

if(i!=-1)

{cout<<"创建OK"<<endl;

cout<<"共创建了"<<i<<"个节点"<<endl;

}

show();

delelte();

insert();

return 0;

}



                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐