Linux下单链表的实现

该单链表在Linux系统GCC编译器下编码调试通过,初学者请多指教。

makefile文件

main:main.o linklist.o
	gcc -o main main.o linklist.o
main.o:main.c 
	gcc -c main.c
linklist.o:linklist.c linklist.h
	gcc -c linklist.c
clean:
	rm *.o main 

main.c主文件

#include 
#include 
#include "linklist.h"
int main()
{
	linklist *mylist = NULL;
	int len = 10;
	ElemType myelem = 0;
	mylist = (linklist *)malloc(sizeof(linklist));	//头指针
	mylist->next = NULL;
	printf("hello world\n");
	CreatList(mylist , len);
	PrintList(mylist);
	if(!InsertList(mylist , 9 , 55)){
		printf("InsertList success!\n");
		PrintList(mylist);
	}
	else { 
		printf("InsertList fail!\n");
	}
	if(!DeleteList(mylist , 1 ,&myelem)){
		printf("DeleteList success!\n");
		printf("the deleted elem is %d\n",myelem);
		PrintList(mylist);
	}
	else { 
		printf("DeleteList success!\n");
	}
	DeleteAllList(mylist);
	PrintList(mylist);
	return 0;
}


linklist.h头文件

#define OK 		0	//no error
#define ERROR 	1	//some error
typedef int ElemType;
typedef struct node{
	ElemType data;
	struct node *next;
}linklist,node;
typedef enum bool{
	ok = 0,
	error = 1
}bool;
void CreatList(linklist *L,int len);
void PrintList(linklist *L);
void DeleteAllList(linklist *L);
bool InsertList(linklist *L , int order , ElemType elem);
bool DeleteList(linklist *L , int order , ElemType *elem);

linklist.c实现文件

#include 
#include 
#include 
#include 
#include "linklist.h"
//创建链表,长度为len
void CreatList(linklist *L,int len)
{
	linklist *p = L;
	int j=0;
	srand(time(0));
	while(j++ < len){
		p=(linklist *)malloc(sizeof(linklist));
		p->data = rand()%100 + 1;
		p->next = L->next;
		L->next = p;
	}
	printf("\nCreatList is finished\n");
}
//打印链表
void PrintList(linklist *L)
{
	linklist *p = L->next;		//指向第一个节点
	if(NULL == p){
		printf("\nLinkList is empty,in PrintList()\n");
		return;}
	else while(NULL != p){
		printf(" %d ",p->data);
		p = p->next;
	}
	printf("\nPrintList Finished\n");
}
//整表删除
void DeleteAllList(linklist *L)
{
	linklist *p = L->next;
	linklist *q = NULL;
	while( NULL != p){
		q = p;
		p = p->next;
		free(q);
	}
	L->next = NULL;
	printf("\nDeleteList Finished\n");
}
//第order位置插入elem元素
bool InsertList(linklist *L , int order , ElemType elem)
{
	linklist *p = L;
	node *q;
	int j = 0;
	while(p && j < order){
		p = p->next;
		++j;}
	if(!p || j > order){
		return ERROR;
	}
	q = (linklist *)malloc(sizeof(linklist));
	q->data = elem;
	q->next = p->next;
	p->next = q;
	return OK;
}
//删除第order个元素,并存入*elem
bool DeleteList(linklist *L , int order , ElemType *elem)
{
	linklist *p = L;
	node *q;
	int j = 0;
	while(p && j < order){
		p = p->next;
		++j;}
	if(!p || j > order){
		return ERROR;
	}
	q = p->next;
	p->next = q->next;
	*elem = q->data;
	free(q);
	return OK;
}   

 
  
 
 

你可能感兴趣的:(数据结构和算法)