我做的一个链表操作,望高手指教
// shiyaner.cpp : Defines the entry point for the console application.//
#include <iostream.h>
#include <string.h>
#define AID 1234
//定义结构体
struct Stu
{
char* StuName ;
int StuID;
Stu* next;
};
typedef Stu List;
//插入中间某一个字节之hou
void InsertToMid(List*ls,char*name,int id)
{
Stu * T = ls ;
//检测节点
if(id==NULL)
return;
//生成新节点
Stu*p = new Stu;
//原链表为空的情况
if(ls==NULL)
{
p=ls->next;
p->next = NULL;
}
//给节点数据项赋值
p->StuID=id;
int nlen = strlen (name)+1;
p->StuName = new char[nlen];
strcpy (p->StuName,name);
//寻找目标节点
while(T->next->StuID!=AID)
{
T=T->next ;
}
//插入
p->next=T->next;
T->next = p ;
}
//输出插入后的函数
void InsertShowList(List * lst)
{
Stu *p = lst->next ;
//标题
cout<<"Name";
cout<<"ID"<<endl;
//输出结构体内容
while (p)
if(p->StuName==NULL)
cout<<" ";
else
cout<<p->StuName ;
cout<< p->StuID<<endl ;
//指向下一个节点
p = p->next;
}
//删除一个节点
void Delete(List * lst,int id )
{
Stu *p = lst ;//the first is null
while (p->next->StuID!= id)
{
Stu * Q=p->next;
p->next = p->next->next;
if(Q->StuName!=NULL)
delete [] Q->StuName;
delete Q;
}
}
//输出删除后的函数
void DeleteShowList(List * lst)
{
Stu *p = lst->next ;
//标题
cout<<"Name";
cout<<"ID"<<endl;
//输出结构体内容
while (p)
if(p->StuName==NULL)
cout<<" ";
else
cout<<p->StuName ;
cout<< p->StuID<<endl ;
//指向下一个节点
p = p->next;
}
//释放空间
void FreeList(List * lst)
{
if(lst==NULL)
return;
//第一个节点为空 从第二个开始
Stu * p= lst->next;
while(p)
{
Stu * T = p;
p=p->next;
if(T->StuName)
delete [] T->StuName;
delete T;
}
lst ->next = NULL ;
}
void main()
{
List ls;
struct Stu a,b,*head;
head = &a;
ls = *head;
a.next = &b;
b.next = NULL;
a.StuID = 1234;
strcpy(a.StuName,"王一");
b.StuID = 1231 ;
strcpy(b.StuName,"王二");
InsertToMid(&ls,"张一",1234);
InsertToMid(&ls,"张二",1235);
InsertShowList(&ls);
DeleteShowList(&ls);
}