C语言单链表的创建(使用函数)
C语言单链表的入门学习
用函数实现上篇文章中建立链表的功能。
将该函数声明为指针函数,返回值为创建链表的链头指针。
node * createlist(void)
将遍历列表的过程也用一个函数来实现。
void display(node * head)
{
node * p;
p = head;
while(p != NULL)
{
printf("%d ",p->num);
p = p->next;
}
printf("\n");
}
使用函数来实现单链表的创建。
#include<stdio.h>
#include<stdlib.h>
typedef struct _node
{
int num;
struct _node * next;
}node;
node * createlist(void);
void display(node * head);
int main(void)
{
node *head;
head = createlist();
display(head);
return 0;
}
node * createlist(void)
{
node * head = NULL, *p, *tail = NULL;
int n;
while(scanf("%d", &n) == 1)//当输入不为整数时结束
{
p = (node *)malloc(sizeof(node));
if(head == NULL)
head = p;
else
tail->next = p;
p->num = n;
p->next = NULL;
tail = p;
}
return head;
}
void display(node * head)
{
node * p;
p = head;
while(p != NULL)
{
printf("%d ",p->num);
p = p->next;
}
printf("\n");
}