用C语言写一段创建单链表的代码
时间: 2024-05-25 12:17:39 浏览: 112
以下是创建单链表的C语言代码:
#include<stdio.h>
#include<stdlib.h>
//定义链表结构体
struct node
{
int data;
struct node *next;
};
typedef struct node NODE;
typedef NODE *LINK;
int main()
{
LINK head = NULL;
LINK tail = NULL;
LINK new_node = NULL;
int num = 0;
//创建链表
printf("请输入一个整数作为链表的元素(输入-1结束):\n");
while(1)
{
scanf("%d",&num);
if(num == -1)
{
break;
}
new_node = (LINK)malloc(sizeof(NODE));
new_node->data = num;
new_node->next = NULL;
if(head == NULL)
{
head = new_node;
tail = new_node;
}
else
{
tail->next = new_node;
tail = new_node;
}
}
//遍历链表
printf("链表的元素为:");
LINK p = head;
while(p != NULL)
{
printf("%d ",p->data);
p = p->next;
}
//释放链表内存
p = head;
while(p != NULL)
{
head = head->next;
free(p);
p = head;
}
return 0;
}
阅读全文