当前位置:文档之家› C++链表的插入删除及查找

C++链表的插入删除及查找

cout<<"请输入字符和插入位置:";
cin>>ch>>n;
Insert(head,ch,n);
break;
}
case 5:
{
cout<<"请输入删除的字符:";
cin>>ch;
Delete(head,ch);
break;
}
case 6:
{
cout<<"请输入查找的字符:";
cin>>ch;
cout<<"该字符第一次出现位置为:"<<Find(head,ch)<<endl;
p=p->next;
if(p->next!=NULL)
{
s->next=p->next;
p->next->last=s;
p->next=s;
s->last=p;
return;
}
p->next=s;
s->last=p;
return;
}
int Find(Node *head,char ch)//查找节点,返回节点位置
{
Node *s,*p;
s=new Node;
s->ch=ch;
s->next=s->last=NULL;
if(head==NULL)
{
head=s;
return;
}
if(n==1)
{
s->next=head;
head->last=s;
head=s;
return;
}
p=head;
for(int i=1;i<n-1&&p->next!=NULL;i++)//p指向n的前一个位置
return;
}
while(q)
{
delete(p);
p=q;
q=q->next;
}
delete p;
head=NULL;
return;
}
void ShowList(Node *head)//输出函数,正向遍历链表
{Байду номын сангаас
Node *p;
if(head==NULL)
{
cout<<"表空!"<<endl;
return;
{
cout<<"表为空!\n";return;
}
if(head->ch==ch)
{
head->next->last=NULL;
head=head->next;
return;
}
p=head;
p=p->next;
while(p)
{
if(p->ch==ch)
{
if(p->next)
{
p->last->next=p->next;
{
Node *p;
int i=1;
p=head;
while(p)
{
if(p->ch==ch)
return i;
p=p->next;
i++;
}
return 0;
}
void Delete(Node *&head,char ch)//删除节点,删除第一个ch字符
{
Node *p;
if(head==NULL)
Node *next;
Node *last;
};
void CreatList(Node *&head)//创建双向链表,引用参数是表头指针
{
char str[100];
cout<<"请输入字符串!"<<endl;//将输入的字符串保存在str数组里
cin>>str;
Node *s,*p;
for(int i=0;str[i];i++)//把每个数组元素包含的字符赋给双向链表的一个节点
}
p=head;
while(p)
{
cout<<p->ch;
p=p->next;
}
cout<<endl;
}
void RShowList(Node *head)//输出函数,反向遍历链表
{
if(head==NULL)
{
cout<<"表空!"<<endl;
return;
}
while(head->next)//让指针指到最后一个节点
p->next->last=p->last;
return;
}
else
{
p->last->next=NULL;
return;
}
}
p=p->next;
}
}
void Del(Node *&head)//销毁链表
{
Node *p,*q;
p=head;
q=p->next;
if(head==NULL)
{
cout<<"表空!"<<endl;
{
head=head->next;
}
while(head)
{
cout<<head->ch;
head=head->last;
}
cout<<endl;
}
int main()
{
Node *head=NULL;
int choice,n;
char ch;
cout<<"1:建立链表2:正向遍历3:反向遍历4:插入字符\n"<<"5:删除字符6:查找字符7:销毁链表0:退出"<<endl;
break;
}
case 7:
Del(head);break;
}
cout<<endl;
cout<<"1:建立链表2:正向遍历3:反向遍历4:插入字符\n"<<"5:删除字符6:查找字符7:销毁链表0:退出"<<endl;
cout<<"请选择操作:";
cin>>choice;
}
}
cout<<"请选择操作:";
cin>>choice;
while(choice)
{
switch(choice)
{
case 1:CreatList(head);break;
case 2:ShowList(head);break;
case 3:RShowList(head);break;
case 4:
{
/*从键盘读入一个字符串,把它存入一个链表(每个结点存储1个字符),并按相反的次序将字符串输出到显示屏。
要求至少写出以下方法或函数,初始化链表、插入结点、删除结点、查找、显示、销毁链表*/
#include<iostream>
using namespace std;
struct Node
{
char ch;
{
s=new Node;
s->ch=str[i];
if(head==NULL)
{
head=s;
head->last=NULL;
}
else
{p->next=s;s->last=p;}
p=s;
}
p->next=NULL;
return;
}
void Insert(Node *&head,char ch,int n)//插入节点,n为插入的位置
相关主题