这次我分享用书本上的逻辑来创建单链表,方便大家学习和理解单链表的创建。
说明:小编也是刚学习这门课程,如有错误,请联系小编,小编及时改正。
以下是代码实现:
#include<stdio.h>
#include<stdlib.h>
//定义结构体
typedef struct Sqlist{
int data;
struct Sqlist* next;
}Sqlist;
//初始化单链表
Sqlist* initlist(){
Sqlist* head=(Sqlist*)malloc(sizeof(Sqlist));
head->next=NULL;
return head;
}
//插入
Sqlist* Insertlist(Sqlist* L,int elem){
Sqlist* new_code = (Sqlist*)malloc(sizeof(Sqlist));
new_code->data=elem;
Sqlist* temp=L;
while (temp->next!=NULL){
temp=temp->next;
}
temp->next=new_code;
new_code->next=NULL;
return L;
}
//查找
Sqlist* Searchlist(Sqlist* L,int elem){
for(int i=0;L!=NULL;i++){
L=L->next;
if (elem==L->data){
printf("%d",L->data);
return 0;
}
}
printf("查找失败,未找到该元素!");
return 0;
}
//删除
Sqlist* Deletelist(Sqlist* L,int elem){
Sqlist* current=L->next;
Sqlist* temp=L;
for (int n=0;current!=NULL;n++){
current=L->next;
if (elem==current->data){
temp->next=current->next;
printf("删除%d成功\n",current->data);
free(current);
return L;
}
temp=current;
current=current->next;
}
printf("删除失败,未找到该元素");
return L;
};
//输出单链表
Sqlist* Printlist(Sqlist* L){
Sqlist* p=L->next;
printf("表内所有元素为:");
for(int k=0;p!=NULL;k++){
printf("%d\t",p->data);
p=p->next;
}
return 0;
}
//释放内存
Sqlist* freelist(Sqlist* L){
Sqlist* temp=NULL;
while (L!=NULL){
temp=L;
L=L->next;
free(temp);
}
return 0;
}
int main(){
Sqlist* list=initlist();
Insertlist(list,10);
Insertlist(list,90);
Deletelist(list,10);
Printlist(list);
freelist(list);
return 0;
}