C++单链表的输入遍历插入删除

#include
using namespace std;
typedef char ElemType;
typedef int Status;
#define OK 1
#define ERROR 0
typedef struct Lnode
{
ElemType data;
struct Lnode *next;
}Lnode,*LinkList;
void Creat_List(LinkList L)//创建单链表并输入元素
{
LinkList p;
char ch;
cout<<"请输入链表元素,并且以输入#表示结束!"<while(cin>>ch&&ch!='#')
{
p=(LinkList)malloc(sizeof(Lnode));
if(!p)
{
cout<<"获取内存失败"<exit(ERROR);
}
p->data=ch;//尾插法
L->next=p;
L=p;
}
L->next=NULL;
}
void output_List(LinkList L)//遍历单链表(输出单链表元素)
{
LinkList p;
p=L->next;
if(p==NULL)
{
cout<<"该链表是空链表!"<exit(ERROR);
}
while(p!=NULL)
{
cout<data<<" ";
p=p->next;
}
}
void List_Delete(LinkList L,int i)//删除指定位置的元素
{
LinkList q;
if(i<1)
{
cout<<"删除位置非法(过小)!"<exit(ERROR);
}
int j=0;
while(L!=NULL&&j{
L=L->next;
j++;
}
if(L->next==NULL)
{
cout<<"删除位置非法(过大)!"<exit(ERROR);
}
q=L->next;
L->next=q->next;
free(q);
}
void List_Inster(LinkList L,int i,ElemType e)//在指定位置插入元素
{
LinkList s;
int j=0;
while(L!=NULL&&j{
L=L->next;
j++;
}
if(!L||j>i-1)
{
cout<<"插入位置非法!"<exit(ERROR);
}
s=(LinkList)malloc(sizeof(Lnode));
s->data=e;
s->next=L->next;
L->next=s;
}
Status main()
{
LinkList H;
H=(LinkList)malloc(sizeof(Lnode));
H->next=NULL;
Creat_List(H);
output_List(H);
int n;
cout<<"请输入要删除的元素的位置!"<cin>>n;
List_Delete(H,n);
cout<<"删除元素后的链表为:"<output_List(H);
cout<<"请输入插入的位置和元素!"<ElemType m;
cin>>n>>m;
List_Inster(H,n,m);
output_List(H);
return 0;
}


相关文档
最新文档