单链表c语言实现

#include <stdio.h>
#include <stdlib.h>

typedef int ElemType;
typedef struct Lnode{
ElemType data;
Lnode *next;
}Lnode,*LinkNode;


int InitLinkNode(LinkNode &L){
L = (LinkNode)malloc(sizeof(Lnode));
L -> next = NULL;
printf("Lnode init success \n");
return 0;
}

int Empty(LinkNode L){
if(!(L->next)){
printf("empty Lnode\n");
return 0;
}
printf("not empty Lnode\n");
return 0;
}

int InsertLinNode(LinkNode &L, int i,ElemType e){
LinkNode p,q;
int j = 0;
p = L;
while(p&&j<i-1){
p = p->next;
j++;
}
if(!p&&j>i-1){
printf("LinkNode error\n");
return 0;
}
q = (LinkNode)malloc(sizeof(Lnode));
q -> data =e;
q ->next = p->next;
p -> next = q;
return 0;
}


int GetAllElem(LinkNode L){
LinkNode p;
p = L;
while(L){
p = p ->next;
printf("%d\n",p->data);
}
return 0;
}

int GetElem(LinkNode L,int i){
int j =0;
ElemType e;
LinkNode p;
p = L;
while(p->next&&j<i-1){
p = p->next;
printf("%d\n",p->data);
j++;
}

e = p->data;
printf("%d\n",e);
return 0;
}

int GetElemByData(LinkNode L, ElemType e){
LinkNode q;
ElemType data;
q = L;
while(q){
if (q->data==e){
printf("find elem in LinkNode %d\n",q->data);
return 0;
}
q = q->next;
}
printf("elem is not in LinkNode\n");
return 0;
}

int DeleteLinkNode(LinkNode &L,int i){
LinkNode p,q;
int j = 0;
p = L;
while(p->next&&j<i-1){
p = p->next;
j ++;
}
if (!(p->next)||j>i-1){
printf("LinkNode range error");
return 0;
}
q = p->next;
p->next = q->next;
return 0;
}

int clearLinkNode(LinkNode &L){
LinkNode p;
while(L){
p = L;
L = L->next;
free(p);
}
return 0;
}

int reloadLinkNode(LinkNode &L){
LinkNode p,q;
p = L->next;
while(p){
q = p->next;
free(p);
p = q;
}
L -> next = NULL;
return 0;
}

int InsertLinkNodeHead(LinkNode &L,int i){
LinkNode p;
int j;
for (int j=i;j>0;j--){
p = (LinkNode)malloc(sizeof(Lnode));
p->data = j;
p -> next = L ->next;
L->next = p;
}
return 0;
}

int InsertLinkNodeTail(LinkNode &L,int i){
LinkNode p,r;
r = L;
for (int j=0;j<i;j++){
p = (LinkNode)malloc(sizeof(Lnode));
p->data = j;
p ->next = NULL;
r -> next = p;
r = p;
}
}


int main(){
LinkNode L;
InitLinkNode(L);
// for (int i=0;i<=10;i++){
// InsertLinNode(L,i+1,i);
// }
InsertLinkNodeTail(L,6);
DeleteLinkNode(L,4);
// DeleteLinkNode(L,1);
InsertLinNode(L,2,22);

// GetElemByData(L,100);
// reloadLinkNode(L);
GetAllElem(L);


Empty(L);
return 0;

}

 

头插法尾插法未完成下周更新完。

posted @ 2022-04-22 18:21  Ccdjun  阅读(35)  评论(0编辑  收藏  举报