请按照输入整数的顺序建立一个带表头节点的链表。已知程序的基本结构如下,请你编写 ins_list 函数。
#include "stdio.h"
#include "stdlib.h"
struct node { int data;
struct node * next;
};
typedef struct node NODE;
typedef struct node * PNODE;
void outlist( PNODE );
void ins_list( PNODE h, int num ) ;
int main ( ){
int num=1;
PNODE head;
head = (PNODE)malloc( sizeof(NODE) );
head->next = NULL;
head->data = -1;
while ( num!=0 ) {
scanf("%d", &num);
if ( num!=0 )
ins_list( head, num);
}
outlist( head );
return 0;
}
void ins_list( PNODE h, int num ){
int i;PNODE p;PNODE q;
if((h->next)==NULL){
p=(PNODE)malloc(sizeof(NODE));
h->next = p;
p->data=num;
p->next = NULL;
}else{
p=h->next;
while((p->next) != NULL){
p = p->next;
}
q=(PNODE)malloc(sizeof(NODE));
p->next = q;
q->next = NULL;
q->data = num;
}
}
void outlist( PNODE head )
{ PNODE p;
p = head->next;
while ( p != NULL )
{ printf("%d\n", p->data);
p = p->next;
}
}
该程序实现了创建一个带有表头节点的链表,并按输入的整数顺序插入节点。在主函数中,首先初始化头节点,然后读取整数,非零数值调用`ins_list`函数插入链表。`ins_list`函数检查链表是否为空,若为空则直接插入,否则在链表尾部插入新节点。最后,`outlist`函数遍历并打印链表中的所有数据。
2397

被折叠的 条评论
为什么被折叠?



