请用c语言创建一个带头节点的单链表,实现输入数据,删除,插入的基本功能
2个回答
展开全部
#include <stdio.h>
#include <malloc.h>
#include <stdlib.h>
typedef struct Node
{
int date;
struct Node * pNext;
}NODE, *PNODE;
//函数声明
PNODE creat_list();//创建链表
void traverse_list(PNODE pHead); //输出链表
void Insert(PNODE pHead,int pos,int e); //pos 为插入位置 e为插入的数据
void Delete(PNODE pHead,int pos,int *e);
//pos 为删除链表第pos个数 e存放被删除的数据
int main()
{
int e;
PNODE pHead = NULL;
pHead = creat_list();
traverse_list(pHead);
Insert(pHead,2,99);
traverse_list(pHead);
Delete(pHead,3,&e);
printf("被删除的数据为 %d\n",e);
traverse_list(pHead);
return 0;
}
PNODE creat_list()
{
int len;//用来存放有效结点的个数
int i;
int val;//用来临时存放有效结点的数据
PNODE pHead = (PNODE)malloc(sizeof(NODE));
//创建一个不存放数据的结点,pHead 为头指针
if (pHead == NULL)
{
printf("内存分配失败,程序终止!\n");
exit(-1);
}
PNODE pTail = pHead;
pTail->pNext = NULL;
printf("请输入你需要生成的链表的个数:len = ");
scanf("%d",&len);
for (i = 0; i < len; i++)
{
printf("请输入第%d个节点的值:",i+1);
scanf("%d",&val);
PNODE pNew = (PNODE)malloc(sizeof(NODE));
//当i = 0 时,创建的第一个结点是首结 每创建一个新结点
if (pNew == NULL)
{
printf("内存分配失败,程序终止!\n");
exit(-1);
}
pNew->date = val;
pTail->pNext = pNew;
pNew->pNext = NULL;
pTail = pNew;
}
return pHead;
}
void traverse_list(PNODE pHead)
{
PNODE p = pHead->pNext;
while(NULL != p)
{
printf("%d ",p->date);
p = p->pNext;
}
printf("\n");
return;
}
void Insert(PNODE pHead,int pos,int e)
{
int j = 0;
PNODE p, s;
p = pHead;
while(p && j < pos - 1)
{
p = p->pNext;
j++;
}
if(!p || j > pos - 1)
exit(-1);
s = (PNODE)malloc(sizeof(NODE));
s->date = e;
s->pNext = p->pNext;
p->pNext = s;
}
void Delete(PNODE pHead,int pos,int *e)
{
int j = 0;
PNODE p, r;
p = pHead;
while(p && j < pos - 1)
{
p = p->pNext;
j++;
}
if(!p->pNext || j > pos - 1)
exit(-1);
r = p->pNext;
p->pNext = r->pNext;
*e = r->date;
free(r);
}
追问
谢谢
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询