C语言单链表

C与C++学习
1.单链表(一)常见操作创建,遍历,逆序,释放
#include<stdio.h>
#include<malloc.h>
/*
struct llist
/
struct llist_node {
int value;
struct llist_node
next;
};
/*
create single llist
/
struct llist_node
create_llist(int number) {
struct llist_node* head = NULL;
int value = 1;
head = (struct llist_node*)malloc(sizeof(struct llist_node));
head->value = value++;
head->next = NULL;
struct llist_node* temp = head;
while (number–)
{
struct llist_node* temp2 = (struct llist_node*)malloc(sizeof(struct llist_node));
temp2->value = value++;
temp2->next = NULL;
temp->next = temp2;
temp = temp->next;
}
return head;
}
/*
List traversal
/
void display_llist(struct llist_node
head) {
while (head)
{
int i=0;
printf(“打印的第%d个数为:%d\n”, ++i, head->value);
head = head->next;
}
}
/*
free llist
/
void free_llist(struct llist_node
head) {
int i = 0;
while (head)
{
struct llist_node* temp = head;
head = head->next;
free(temp);
printf(“release number is %d\n”, ++i);
}

}
/*
reverse llist
/
struct llist_node
reverse_llist(struct llist_node* head) {
struct llist_node* new_head = NULL;
while (head)
{
struct llist_node* tmp = head;
head = head->next;
tmp->next = new_head;
new_head = tmp;
}
return new_head;
}
/*
test
/
int main()
{
struct llist_node
head = NULL;
int n = 10;
head = create_llist(10);
display_llist(head);
head = reverse_llist(head);
printf(“链表逆序后打印结果\n”);
display_llist(head);
free_llist(head);
return 0;
}
链表逆序思路:
第一次循环将第一个节点结点指向NULL,此后每循环一次,让后面的节点指向前面的节点。C语言单链表

运行结果:
C语言单链表