單鏈表創建及其插入,刪除,逆序
#include <iostream.h>
struct node
{
char data;
node *next;
};
void Output(node *list);
void Init(node *list)
{
// list->data='0';
list->next=NULL;
}
void CreateList(node *list)
{
int a=1;
char x;
node *p,*s;
p=list;
cout<<"輸入數據,#結束"<<endl;
while(a)
{
cin>>x;
if(x!='#')
{
s=new node;
s->data=x;
p->next=s;
s->next=NULL;
p=s;
}
else a=0;
}
}
void Insert(node *list,char insertnum)
{
char z;
node *p,*s;
p=list;
Output(list);
cout<<"請指出需要將數據插入哪個數據之後:"<<endl;
cin>>z;
s=new node;
s->data=insertnum;
while(p->data!=z)
{
p=p->next;
}
if(p->next==NULL)
{
p->next=s;
s->next=NULL;
}
else
{
s->next=p->next;
p->next=s;
}
cout<<"插入之後結果爲:"<<endl;
Output(list);
}
void Delete(node *list)
{
char z;
node *p;
p=list;
Output(list);
cout<<"請指出需要將哪個數據刪除:"<<endl;
cin>>z;
while(p->next->data!=z)
{
p=p->next;
}
if(p->next->next==NULL)
{
p->next=NULL;
}
else
{
p->next=p->next->next;
}
Output(list);
}
//單鏈表的逆序
void reverse(node *list)
{
node *p,*q,*r;
q=NULL;
p=list->next;
while(p)
{
r=p->next;
p->next=q;
q=p;
p=r;
}
list->next=q;
Output(list);
}
void Output(node *list)
{
node *q;
q=list->next;
while(q->next)
{
cout<<q->next->data<<" ";
q=q->next;
}
}
void main()
{
node *list=new node;
Init(list);
CreateList(list);
//Output(list);
//Insert(list,'5');
//Delete(list);
reverse(list);
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.