#include<stdio.h>
#include<malloc.h>
#include<stdlib.h>
typedef struct Node
{
int xh;
int nl;
char name;
struct Node *pNext;
}NODE , *PNODE;
PNODE create_list (void);
bool insert_list(PNODE pHead,int pos,int xh,char name,int nl);
bool delete_list (PNODE pHead,int pos,int *xh,char *name ,int* nl);
void traverse_list (PNODE pHead);
int main()
{
int pos1,pos2,xh1,xh2,nl1,nl2;
char name1,name2;
PNODE pHead=NULL;
pHead=create_list();
printf("该链表为:\n");
traverse_list(pHead);
printf("请输入你要增添的链表的位置和该位置对应的学号、姓名、年龄:");
scanf("%d%d%s%d",&pos1,&xh1,&name1,&nl1);
insert_list(pHead,pos1,xh1,name1,nl1);
printf("您增添后的链表为:\n");
traverse_list(pHead);
printf("请输入你要删除的链表的位置和该位置对应的学号、名字、年龄:");
scanf("%d%d%s%d",&pos2,&xh2,&name2,&nl2);
if(delete_list(pHead,pos2,&xh2,&name2,&nl2))
{
printf("删除成功,您删除的学号是%d,姓名为%s,年龄为%d",xh2,name2,nl2);
printf("您删除后的链表为:\n");
traverse_list(pHead);
}
else
{
printf("删除失败\n");
}
return 0;
}
PNODE create_list (void)
{
int len;
int i;
int xh;
int nl;
char name;
PNODE pHead=(PNODE)malloc(sizeof(NODE));
if(pHead==NULL)
{
printf("内存分配失败,程序终止\n");
exit(-1);
}
PNODE Tail=pHead;
Tail->pNext =NULL;
printf("请输入您要生成链表的长度:len=");
scanf("%d",&len);
for(i=0;i<len;i++)
{
printf("请输入第%d个学生的学号、姓名、年龄:",i+1);
scanf("%d %s %d",&xh,&name,&nl);
PNODE pNew=(PNODE)malloc(sizeof(NODE));
if(pNew==NULL)
{
printf("内存分配失败,程序终止\n");
exit(-1);
}
pNew->xh =xh;
pNew->name =name;
pNew->nl =nl;
pNew->pNext =NULL;
Tail->pNext =pNew;
Tail=pNew;
}
return pHead;
}
bool insert_list(PNODE pHead,int pos,int xh,char name,int nl)
{
int i=0;
PNODE p=pHead;
while(p!=NULL &&i<pos-1)
{
p=p->pNext ;
i++;
}
if(i>pos-1 ||p==NULL)
{
return false;
}
PNODE pNew=(PNODE)malloc(sizeof(NODE));
if(pNew==NULL)
{
printf("内存分配失败,程序终止\n");
exit(-1);
}
pNew->xh =xh;
pNew->name =name;
pNew->nl =nl;
PNODE q=p->pNext ;
p->pNext =pNew;
pNew->pNext =q;
return true;
}
bool delete_list (PNODE pHead,int pos,int *xh,char *name ,int* nl)
{
int i=0;
PNODE p=pHead;
while(p!=NULL &&i<pos-1)
{
p=p->pNext ;
i++;
}
if (p==NULL ||i>pos-1)
{
return false;
}
PNODE q=p->pNext ;
*xh=q->xh ;
*name=q->name ;
*nl=q->nl ;
p->pNext =p->pNext ->pNext;
free(q);
q=NULL;
return true;
}
void traverse_list (PNODE pHead)
{
if(pHead==NULL)
{
printf("该链表为空:");
return;
}
PNODE p=pHead->pNext ;
while(p!=NULL)
{
printf("%d %s %d\t",p->xh ,p->name ,p->nl );
p=p->pNext ;
}
printf("\n");
}
这个链表为什么遍历不了?
最新推荐文章于 2024-11-04 21:43:20 发布