#include <stdio.h>#include <stdlib.h>struct number{ int shu; struct number *next;};struct number *create(int length){ struct number *head; struct number *p1,*p2; int i; p1=p2=(struct number *)malloc(sizeof(struct number)); p1->shu=1; head=p1; for(i=2;i<=length;i++) { p1=(struct number *)malloc(sizeof(struct number)); p1->shu=i; p2->next=p1; p2=p1; } p1->next=NULL; return (head); }struct number *del_3(struct number *head,int length){ struct number *p,*temp; int count=2; p=head; while(length>1) { if(count%3==0) { count=1; temp=p->next; p->next=temp->next; free(temp); p=p->next; length--; } else? p=p->next; count++; } return (p);}void print(struct number *p){ printf("%d\n",p->shu);}int main(){ int length ; struct number *head,*p; printf("input length: "); scanf("%d",&length); head=create(length); p=del_3(head,length); print(p); return 0;}
1 回答

onemoo
TA貢獻883條經驗 獲得超454個贊
在del_3中,你用temp和p依次指向后面的元素,但你沒有注意判斷是否臨近最后一個元素。
如果p已經指向了最后一個元素,那么temp = p->next就是NULL,隨后再 temp->next 試圖訪問NULL會發生segmentation fault。
while中的length并沒有能夠很好地判斷剩余元素的個數,因為在if的else分支中,p仍然前進了,但length沒有做相應的變化。
- 1 回答
- 0 關注
- 1463 瀏覽
添加回答
舉報
0/150
提交
取消