//遍歷一般線性表,刪除位於鍵值為負節點之後的所有節點
#include
#include
#include
#include
struct example
{
int input;
struct example* next;
};
typedef struct example EXAMPLE;
void creat (EXAMPLE* head);
void remove (EXAMPLE* head);
void print (EXAMPLE* head);
int main (void)
{
EXAMPLE* head;
creat (head);
// print (head); 單獨調用這個函數的話就不行,但是把源代碼拷到creat中執行就行,為什麼會這樣?
remove(head); //這個函數有錯誤,但找不到哪裡出錯了
// print (head);
return 0;
}
//---------------creat-------------------
void creat (EXAMPLE* head)
{
EXAMPLE* p;
EXAMPLE* pre;
int i;
int n;
head = (EXAMPLE*)malloc(sizeof(EXAMPLE));
printf("n: ");
scanf("%d",&n);
i = 1;
printf("input: ");
scanf("%d", &head->input);
i++;
pre = head;
for(;i <= n; i++)
{
p = (EXAMPLE*)malloc(sizeof(EXAMPLE));
printf("input: ");
scanf("%d", &p->input);
pre->next = p;
p->next = NULL;
pre = p;
}
//打印
p = head;
while(p)
{
printf("%d\n",p->input);
p = p->next;
}
return;
}
//-----------------remove-----------------
void remove (EXAMPLE* head)
{
EXAMPLE* p;
EXAMPLE* pon;
EXAMPLE* pre;
//確定pon的位置
if(head->input < 0)
{
pon = head->next;
head->next = NULL;
}
else
{
p = head;
while(1)
{
if((p->next)->input < 0)
{
pon = p->next;
p->next = NULL;
break;
}
if(!(p->next))
{
pon = NULL;
break;
}
p = p->next;
}
}
//刪除pon(包含在內)之後的所有節點
pre = pon;
while(pre)
{
pre = pon->next;
free(pon);
pon = pre;
}
//打印
p = head;
while(p)
{
printf("%d\n",p->input);
p = p->next;
}
return;
}
//------------print-----------------
void print (EXAMPLE* head)
{
EXAMPLE* p;
p = head;
while(p)
{
printf("%d\n",p->input);
p = p->next;
}
return;
}
第一,head指針的值要從 creat 函數中傳出,參數必須要指向指針的指針。這是你 print 函數無效的原因,因為 head 指針的數值不對。