當前位置:編程學習大全網 - 編程軟體 - C語言中如何用free清除壹串鏈表

C語言中如何用free清除壹串鏈表

#include?<stdio.h>

#include?<stdlib.h>

struct?Node{

int?con;

Node?*next;

};

Node*?insert(Node?*h,int?a,int?pos)//這裏,增加返回類型

{

Node?*p=(Node?*)malloc(sizeof(Node));

Node?*pt=h;

if?(pos==0)?

{

p->con=a;

p->next=h;

h?=?p;

}

else

{

for(int?i=1;i<pos;i++)//這裏,如果pos值輸入大於節點個數,會導致越界,自己修改

{

pt=pt->next;

}

p->con=a;

p->next?=?pt->next;

pt->next=p;

}

return?h;//這裏,返回地址

}

int?main()

{

int?i;

int?count=0;

puts("Enter?num");

scanf("%d",&i);

Node?*p=(?Node?*)malloc(sizeof(?Node));

Node?*head=p;

p->next=NULL;

p->con=i;

Node?*c=head;

puts("Next?one,nonnum?to?stop");?

while(scanf("%d",&i)==1)

{

fflush(stdin);

p=(struct?Node*)malloc(sizeof(struct?Node));

p->con=i;

c->next=p;

p->next=NULL;

c=p;

puts("Next?one,nonnum?to?stop");

}

fflush(stdin);

int?a,pos;?

puts("insert?a?at?pos");

scanf("%d?%d",&a,&pos);

head?=?insert(head,a,pos);//這裏,地址傳出來

c=head;

while(c!=NULL)?

{

printf("%d?%d\n",count,c->con);

count++;

c=c->next;

}

c=head;?

Node?*tmp;

while(c!=NULL)//here,多了個分號,內存釋放需要改

{

tmp?=?c;

c=c->next;

free(tmp);

}

return?0;

}

  • 上一篇:外星人燈籠軟件開機加載慢
  • 下一篇:c編程:有壹個壹維數組,存放10個學生成績,編寫程序,求出平均分,最高分和最低分,並輸出
  • copyright 2024編程學習大全網