王道c语言ch11-单链表的新建、插入、删除例题
王道c语言ch11-单链表的新建、插入、删除例题
#include <stdio.h>
#include <stdlib.h>
#define END 33
typedef int ElemType;
typedef struct LNote {
ElemType data;
struct LNote *next;
} LNote, *LinkList;
//头插法
void list_head_insert(LinkList &L) {
ElemType x;
L = (LinkList) malloc(sizeof(LNote));
L->next = NULL;
scanf("%d", &x);
while (x != END) {
LinkList s = (LinkList) malloc(sizeof(LNote));
s->data = x;
s->next = L->next;
L->next = s;
scanf("%d", &x);
}
}
//尾插法
void list_tail_insert(LinkList &L) {
ElemType x;
L = (LinkList) malloc(sizeof(LNote));
L->next = NULL;
scanf("%d", &x);
LinkList s,r=L;
while (x != END) {
s = (LinkList) malloc(sizeof(LNote));
s->data = x;
r->next = s;
r=s;
scanf("%d", &x);
}
r->next=NULL;
}
//打印单链表中所有结点的值
void list_print(LinkList P){
P=P->next;
printf("LinkList is :");
while (P!=NULL){
printf("%d ",P->data);
P=P->next;
}
printf("\n");
}
//按位查找,返回结点
LinkList GetElem(LinkList L,int post){
int i=0;
if (post<0){ //post<0返回NULL post=0返回头指针
return NULL;
}
while (L&&i<post){
L=L->next;
i++;
}
return L;
}
//按值查找,返回结点
LinkList LocateElem(LinkList L,ElemType data){
while (L){
L=L->next;
if(L->data == data){
return L;
}
}
return NULL;
}
//往post的位置插入结点
bool InsertElem(LinkList L,int post,ElemType InsertData){
LinkList ret = GetElem(L,post-1);
if (ret){
LinkList s=(LinkList) malloc(sizeof (LNote));
s->data=InsertData;
s->next=ret->next;
ret->next=s;
return true;
} else{
return false;
}
}
//删除结点
bool ListDelete(LinkList L,int i){ //不改变头结点,则不用加引用
LinkList p= GetElem(L,i-1); //i=1,返回头指针
//当i<=0,p=NUll,则LinkList q=p->next;会报错
if(NULL==p){
return false;
}
LinkList q=p->next; //不直接q->next=q->next->next;是为了释放删掉的结点内存
p->next=q->next;
free(q);
return true;
};
int main() {
LinkList L;
list_tail_insert(L);
bool ret = InsertElem(L,2,66);{
if (ret){
printf("insert is ture");
} else{
printf("insert is fault");
}
}
list_print(L);
LinkList search = GetElem(L,2);
if(search){
printf("function of GetElem return %d\n",search->data);
} else{
printf("function of GetElem return null\n");
}
LinkList getdata = LocateElem(L,2);
if(getdata){
printf("function of LocateElem return %d\n",getdata->data);
} else{
printf("function of LocateElem return null\n");
}
ListDelete(L,4);list_print(L);
return 0;
}
clion快捷键:
alt+1 打开文件列表
alt+7 查看函数列表
ctrl shift ± 打开/折叠所有函数