//带头结点单链表的实现
#include<stdio.h>
#include<malloc.h>
typedef struct LinkListNode
{
int data;
struct LinkListNode *next;
}Node,*pNode;
pNode Create(void); //初始化,创建头结点
int Isempty(pNode); //判断链表是否为空
void Traverse(pNode); //遍历
int ListLen(pNode); //求链表长
int Insert(pNode,int pos,int e); //元素插入
int Delete(pNode,int pos,int *e); //元素删除
int main()
{
int val; //用于返回删除元素
pNode pHead=NULL;
pHead=Create();
if(Isempty(pHead)) //判断链表是否为空
printf("链表为空!\n");
else printf("链表不空!\n");
Insert(pHead,1,3);
Insert(pHead,1,2);
Insert(pHead,1,1);
Traverse(pHead);
if(Delete(pHead,3,&val)) printf("删除的元素为:%d\n",val);
else printf("删除失败!\n");
Traverse(pHead); //遍历
printf("链表长为:%d\n",ListLen(pHead));
return 0;
}
//创建头结点,返回结点地址
pNode Create()
{
pNode pHead=(pNode)malloc(sizeof(Node));
pHead->next=NULL;
return pHead;
}
//判断链表是否为空
int Isempty(pNode pHead)
{
if(pHead->next==NULL)
return 1;
else return 0;
}
//遍历
void Traverse(pNode pHead)
{
pNode p;
if(Isempty(pHead))
printf("链表为空!\n");
else
{
printf("遍历结果为:");
for(p=pHead->next;p!=NULL;p=p->next)
printf("%d ",p->data);
printf("\n");
}
}
//求链表长
int ListLen(pNode pHead)
{
int i=0;
pNode p;
p=pHead;
while(p->next!=NULL)
{
i++;
p=p->next;
}
return i;
}
//在第pos个位置插入元素,i为1到表长加一
int Insert(pNode pHead,int pos,int e)
{
int i=0;
pNode p=pHead;
pNode pNew;
while(p!=NULL&&i<pos-1) //判断插入位置是否合理
{
p=p->next;
i++;
}
if(i>pos-1||p==NULL)
return 0;
else
{
pNew=(pNode)malloc(sizeof(Node));
pNew->data=e;
pNew->next=p->next;
p->next=pNew;
return 1;
}
}
//元素删除
int Delete(pNode pHead,int pos,int *pval)
{
pNode p;
pNode q;
int i=0;
p=pHead;
while(p->next!=NULL&&i<pos-1)
{
p=p->next;
i++;
}
if(i>pos||p->next==NULL)
return 0;
else
{
q=p->next;
p->next=p->next->next;
*pval=q->data;
free(q);
q=NULL;
return 1;
}
}
(C语言)线性表的链式存储的实现
最新推荐文章于 2022-09-21 22:42:42 发布