C语言单链表定义及各类操作

#include 
#include 
#include 
typedef int ElemType;

typedef struct LNode{
	ElemType data;//数据域
	struct LNode *next;//指针域
}LinkList;
//初始化单链表
int InitList(LinkList *L){
	// L=(LinkList *)malloc(sizeof(LinkList));
	if (L==NULL) return 0;//分配失败
	L->next=NULL;//空表,类似于顺序表n=0
	printf("初始化完成\n");
}
//插入操作
int ListInsert(LinkList *L,int j,ElemType item){
	if(j<1){
		return 0;
	}

	int i=0;//控制temp指向
	LinkList *temp;//表示链表
	temp=L;//指向L

	//使中间变量指向目标结点
	while(temp!=NULL && inext;
		i++;
	}

	if( temp==NULL ) return 0;//temp下一节点为空(i值过大,不合法),返回

	struct LNode *s;//表示结点
	s=(struct LNode *)malloc(sizeof(struct LNode));//分配内存空间

	s->next=temp->next;//s后续结点为temp当前结点后续结点
	s->data=item;//s当前值为目标值
	temp->next=s;//temp下一节点指向s

	printf("insert successfully\n");

	return 1;
}
//删除操作
int ListDelect(LinkList *L,int j){
	LinkList *temp=L;//指向头结点
	struct LNode *s;//规范
	int k=0;

	while(knext;
	}
	if (temp->next==NULL) return 0;//目标为空非法操作

	s=temp->next;//将目标赋值给s
	temp->next=temp->next->next;//跳过目标
	free(s);//释放存放目标的s
	
	printf("delect successfully\n");

	return 1;
}
//按值查找
struct LNode *LocateELem(LinkList *L,ElemType item){
	LinkList *temp=L;//中间变量来遍历

	//开始查找
	while(temp->data!=item && temp->next!=NULL) temp=temp->next;

	return temp;//返回目标结点
}
//按位查找,返回目标结点
struct LNode *GetElem(LinkList *L,int j){
	if(j<1) return NULL;//短路提前判断

	LinkList *temp=L;//中间变量
	int k=0;//控制链表循环次数

	while(temp!=NULL&&knext;
		temp->data=k+1;
		k++;
	}

	return temp;//返回结点
}
//头插法创建链表
int HeadCreateList(LinkList *L,ElemType k){
	if(k<1) return 0;
	LinkList *temp;
	
	if (temp==NULL) return 0;//分配失败
	
	
	int i=0;
	
	while(idata=i;//交替指向添加元素
		temp->next=L->next;//链表循环赋值
		L->next=temp;
		i++;
	}
	printf("Created successfully\n");
}
//尾插法创建链表
int FootCreatList(LinkList *L,ElemType k){
    //非法操作或创建失败
    if(k<0) return 0;
    LinkList *temp;
    int i=1;
    while(i<=k){
        temp=(LinkList *)malloc(sizeof(LinkList));
        if(temp==NULL) return 0;
        temp->data=i;
        L->next=temp;
        L=L->next;//链表位置始终保持在最后
        i++;
    }
    printf("Created successfully\n");
}

 

//打印操作
void PrintList(LinkList *L){
	LinkList *temp=L;
	temp=temp->next;//从头结点指向首结点
	while(temp!=NULL){
		printf("%d\n",temp->data);
		temp=temp->next;
	}
	printf("print successfully\n");
}
int main(){
	LinkList *L;//声明一个指向单链表的带头指针L
	L=(LinkList *)malloc(sizeof(LinkList));
	InitList(L);//初始化
	HeadCreateList(L,10);//尾插法创建元素
	PrintList(L);

	ListInsert(L,3,16);
	PrintList(L);

	ListDelect(L,7);
	PrintList(L);

	return 0;
}

你可能感兴趣的:(数据结构,C语言程序设计,链表,c语言,数据结构)