请用C语言写一个单链表程序
时间: 2024-05-19 07:14:52 浏览: 97
c语言单链表程序
好的,以下是一个简单的单链表程序示例,使用C语言编写:
#include <stdio.h>
#include <stdlib.h>
struct node {
int data;
struct node* next;
};
int main() {
struct node* head = NULL;
struct node* second = NULL;
struct node* third = NULL;
// allocate 3 nodes in the heap
head = (struct node*)malloc(sizeof(struct node));
second = (struct node*)malloc(sizeof(struct node));
third = (struct node*)malloc(sizeof(struct node));
// assign data to 1st node
head->data = 1;
// link the 1st node with the 2nd node
head->next = second;
// assign data to 2nd node
second->data = 2;
// link the 2nd node with the 3rd node
second->next = third;
// assign data to 3rd node
third->data = 3;
// terminate the 3rd node with a NULL pointer
third->next = NULL;
// display the list
struct node* ptr = head;
while (ptr != NULL) {
printf("%d -> ", ptr->data);
ptr = ptr->next;
}
printf("NULL");
return 0;
}
阅读全文