请按照输入整数的顺序建立一个带表头节点的链表。
程序的基本结构见预设代码。请编写并提交你编写的函数 ins_list()。
预设代码
前置代码
- /* PRESET CODE BEGIN - NEVER TOUCH CODE BELOW */
- #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 outlist( PNODE head )
- { PNODE p;
- p = head->next;
- while ( p != NULL )
- { printf("%d\n", p->data);
- p = p->next;
- }
- }
- /* This is an example for list. Please programme your code like it.
- ins_list( PNODE h, int num )
- {
- .....
- }
- */
- /* PRESET CODE END - NEVER TOUCH CODE ABOVE */
测试输入 | 期待的输出 | 时间限制 | 内存限制 | 额外进程 | |
---|---|---|---|---|---|
测试用例 1 | 以文本方式显示
| 以文本方式显示
| 1秒 | 64M | 0 |
#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 outlist( PNODE head ) {
PNODE p;
p = head->next;
while ( p != NULL ) {
printf("%d\n", p->data);
p = p->next;
}
}
void ins_list( PNODE h, int num ) {
PNODE p, q;
p = h;
while (p->next != NULL)
p = p->next;
q = (PNODE)malloc(sizeof(NODE));//创建新结点
q->data = num;
p->next = q;
q->next = NULL;
}