创建单项链表
链表是动态分配存储空间的链式存储结构,其中包括一个“头指针”变量,头指针中存放一个地址,该地址指向一个元素。链表中每一个元素称为“节点”,每个节点都由两部分组成,即存储数据元素的数据域和存储直接后继存储位置的指针域。指针域中存储的即是链表的下一个节点的位置,是一个指针。多个节点构成一个链表。
#include<stdio.h>
#include<malloc.h>
//声明struct LNode类型,代码如下:
struct LNode {
int data;
struct LNode *next;
};
//自定义函数create
struct LNode *create(int n) {
int i;
struct LNode *head, *p1, *p2;
int a;
head = NULL;
printf("输入整数:\n");
for (i = n; i > 0; i--) {
p1 = (struct LNode*)malloc(sizeof(struct LNode));
scanf("%d", &a);
p1->data = a;
if (head == NULL) {
head = p1;
p2 = p1;
}
else
{
p2->next = p1;
p2 = p1;
}
}
p2->next = NULL;
return head;
}
//在main函数中调用自定义函数create()
int main() {
int n;
struct LNode *q;
printf("输入你想创建的节点个数:");
scanf("%d", &n);
q = create(n);
printf("结果是:\n");
while (q) {
printf("%d ", q->data);
q = q->next;
};
printf("\n");
}
运行结果如图: