数据结构链表
注:“->”是一个整体,它是用于指向结构体子数据的指针,用来取子数据。
结构体类型为
注:struct LNode *pHead=(struct LNode *)malloc(sizeof(struct LNode));//malloc函数动态分配
typedef struct LNode{
Student data; //数据域
struct LNode *pNext;//指针域
}LNode
//创建一个链表
struct LNode *create_list(void)
{
int i;
struct LNode *pHead=(struct LNode *)malloc(sizeof(struct LNode));//生成一个头节点,把地址赋给头指针,头指针指向头节点
if(NULL==pHead)//pHead是存放头指针的地址,若地址不存在则说明赋值失败
{
printf("分配失败!!终止程序\n");
exit(-1);
}
return pHead;//只有返回头指针才能继续使用该链表
}
//遍历程序
void traverse_list(struct LNode*pHead)//遍历程序
{
struct LNode *p=pHead->pNext;
while(NULL!=p)//判断链表是否为空
{
printf("%s %s %d\n",p->data.no,p->data.name,p->data.price);
p=p->pNext;
}
printf("\n");
}
//删除链表中的数值
bool delete_list(struct LNode*pHead,int location)
{
int i=0;
struct LNode *p=pHead;
while(NULL!=p->pNext&&i<location-1)
{
p=p->pNext;
++i;
}
if(i>location-1||NULL==p->pNext)//若要删除第五个则要找到第四个节点的位置
return false;
struct LNode *q=p->pNext;
p->pNext=p->pNext->pNext;
free(q);
q=NULL;
return true;
}
//求链表的长度
int length_list(struct LNode*pHead) //求链表的长度
{
struct LNode *p=pHead->pNext;
int len=0;
while(NULL!=p)
{
++len;
p=p->pNext;
}
return len;
}
//链表数据查找
struct LNode* LocateElem_list(struct LNode *pHead,char n[])
{
struct LNode *p;
int i;
int len=length_list(pHead);//调用 length_list函数得到链表的长度
for(i=0,p=pHead->pNext;i<len-1;++i,p=p->pNext)
if (strcmp(p->data.name,n)==0) //如果n==p->date.name 就返回p
return p;
return 0;
}
//插入一个节点
bool ListInsert_list(LinkList pHead,int a,Student e)
{
int i=0;
struct LNode *p=pHead;
while(NULL!=p&&i<a-1)//若要第五 个则要找到第四个节点的位置
{
p=p->pNext;
++i;
}
if(i>a-1||NULL==p)
return false;
struct LNode *pNew=(struct LNode*)malloc(sizeof(struct LNode));//生成一个新节点
if(NULL==pNew)//判断节点是否生成
{
printf("动态分配内存失败!!\n");
exit(-1);
}
memset(pNew->data.name,'\0',sizeof(pNew->data.name));
memset(pNew->data.no,