您的位置:首页 > 理论基础 > 数据结构算法

链表

2016-05-03 21:11 375 查看
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#define Error -10000
struct LNode
{
int data;
struct LNode *next;
};
struct LNode* InitList()
{
struct LNode *phead;
phead=(struct LNode *)malloc(sizeof(struct LNode));
phead->next=NULL;
return phead;
}
void DestroyList(struct LNode *l)
{
struct LNode *p;
while(l!=NULL)
{
p=l->next;
free(l);
l=p;
}
}
int ListLength(struct LNode *l)
{
int cnt=0;
l=l->next;
while(l!=NULL)
{
cnt++;
l=l->next;
}
return cnt;
}
void ListInsert(struct LNode *l,int e)
{
struct LNode *pnew;
pnew=(struct LNode *)malloc(sizeof(struct LNode));
pnew->data=e;
pnew->next=l->next;
l->next=pnew;
}
void deleteList(struct LNode *l,int id)
{
int cnt=0;
while(l->next!=NULL)
{
cnt++;
if(cnt==id)
{
struct LNode *p;
p=l->next;
l->next=l->next->next;
free(p);
}
l=l->next;
}
}
int LocateList(struct LNode *l,int e)
{
int cnt=0;
while(l->next!=NULL)
{
cnt++;
if(l->next->data==e)
{
return cnt;
}
l=l->next;
}
return Error;
}
int GetList(struct LNode *l,int id)
{
int cnt=0;
while(l->next!=NULL)
{
cnt++;
if(cnt==id)
return l->next->data;
}
return Error;
}
void DisplayList(struct LNode *l)
{
while(l->next!=NULL)
{
printf("%d ",l->next->data);
l=l->next;
}
printf("\n");
}
int main()
{
struct LNode *phead;
phead=InitList();
ListInsert(phead,1);
ListInsert(phead,2);
ListInsert(phead,3);
ListInsert(phead,4);
ListInsert(phead,5);
DisplayList(phead);
deleteList(phead,3);
DisplayList(phead);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  数据结构