//遍历一般线性表,删除位于键值为负节点之后的所有节点
#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;
}