This blog will introduce the creation, deletion, sorting, insertion, search, and length
of a simple singly linked list as an example, this linked list only stores one int, and the header node of the linked list does not store data
main function
#include <stdio.h>
#include <stdlib.h>
typedef struct node
{
int num; //数据域
struct node *next; //指针域
}Node;
int main(int argc, char const *argv[])
{
Node *Head;
Head=Set(); //创建链表
/* ··· */ //这里是所需的的其他操作
return 0;
}
create
End when 0 is entered
Node *Set(void){
Node *Head=(Node *)malloc(sizeof(Node));
Head->next=NULL;
Node *pre=NULL,*t=pre,*p;
while(1){
p=(Node *)malloc(sizeof(Node));
p->next=NULL;
scanf("%d",&p->num);
if(p->num==0){
free(p);
break;
}
if(pre==NULL)
pre=p;
else{
t->next=p;
}
t=p;
}
Head->next=pre;
return Head;
}
delete
Delete all nodes with a value of nu
void Del(Node *Head,int nu){
Node *t=Head;
Node *p=Head->next;
while(p){
if(p->num==nu){
t->next=p->next;
free(p);
p=t->next; //继续向后删 删除所有num=nu的结点
}
else{
t=p;
p=p->next; //若不相等,继续向后找
}
}
}
ask for length
int Len(Node *Head){
int count=0;
Node *t=Head->next;
while(t){
t=t->next;
count++;
}
return count;
}
Print the information of the linked list according to the required
void Show(Node *Head){
Node *t=Head->next;
while(t){
printf("%d ",t->num);
t=t->next;
}
printf("\n");
}
sort
Regarding sorting, I have written a more detailed blog on bubble sorting. Bubble sorting of
singly linked lists
insert
Add a node, the new node num value is n
tail plug
void Add(Node *Head,int n){
Node *t=Head->next;
Node *p=(Node *)malloc(sizeof(Node));
p->num=n;
p->next=NULL;
while(t->next){
t=t->next;
}
t->next=p;
}
head plug
void Add2(Node *Head,int n){
Node *p=(Node *)malloc(sizeof(Node));
p->num=n;
p->next=Head->next;
Head->next=p;
}
find
Find the node whose num value is n in the linked list, and return the node if found, and return NULL if not found
Node *Find(Node *Head,int n){
Node *t=Head->next;
while(t){
if(t->num==n)
break;
t=t->next;
}
return t;
}