今年暑假正式开始我的数据结构学习之旅,虽然之前学过一遍了,但是感觉完全是应付考试,没有认真学
所以,今年打算从头到尾正式学习一遍,每天持续更新学习成果。今天重温了一下链表,分享。
#include<stdio.h>
#include<malloc.h>
typedef struct Node
{
int data;
int len;
struct Node *pnext;
} Node,*pnode;
pnode CreateNode()
{
pnode phead=(pnode)malloc(sizeof(Node));
if(phead==NULL)
{
printf("fail to allocate memory");
return -1;
}
phead->pnext=NULL;
printf("please input some number q to quit:\n");
int n;
pnode ph=phead;
for(int i=0; i<5; i++)
{
pnode p=(pnode)malloc(sizeof(Node));
if(p==NULL)
{
printf("fail to allocate memory");
return -1;
}
p->data=(i+2)*19;
phead->pnext=p;
p->pnext=NULL;
phead = p;
}
return ph;
}
int list(pnode head)
{
int count=0;
printf("遍历结果:\n");
while(head->pnext!=NULL)
{
printf("%d\t",head->pnext->data);
head=head->pnext;
count++;
}
printf("链表长度为:%d\n",count);
return count;
}
void InSert(pnode head,int count)
{
int n,number,c=1;
printf("请输入插入位置:\n");
scanf("%d",&n);
if(n>count+1)
{
printf("超过链表范围\n");
exit(-1);
}
printf("请输入插入的数:");
scanf("%d",&number);
pnode p=(pnode)malloc(sizeof(Node));
p->data=number;
while(c<n)
{
head=head->pnext;
c++;
}
p->pnext=head->pnext;
head->pnext=p;
}
void Delete(pnode head)
{
int n;
int m=0;
printf("请输入想要删除的数字:");
scanf("%d",&n);
while(head->pnext!=NULL)
{
if(head->pnext->data==n)
{
head->pnext=head->pnext->pnext;
m=1;
}
head=head->pnext;
if(head==NULL)
break;
}
if(m==0)
printf("没有找到想要删除的数字\n");
}
int main()
{
pnode p=CreateNode();
int m=list(p);
Delete(p);
list(p);
free(p);
return 0;
}
我是在linux下codeblocks环境下,之前因为没有最后free(节点)导致内存爆满,直接死机了,希望注意这点。