首页 > 代码库 > 链表基本操作集合

链表基本操作集合

链表基本操作集合


//List code by Denis

#include <stdio.h>
#include <malloc.h>
#define ture 1 
#define false 0

typedef int ElemType;
typedef struct list{
	ElemType data;
	struct list *next;
}LNode;
 


//Create a list,nLength is the length of the line list
LNode *Create(int nLength)
{
	int i;
	LNode *Ln_Head,*Ln_tmp1,*Ln_tmp2;
	Ln_Head = (LNode *)malloc(sizeof(LNode));
	Ln_tmp1 = Ln_Head;   /*Save the Head pointor*/
	printf("Input %d data\n",nLength);
	for(i=0;i<nLength;i++)
	{	
		Ln_tmp2 = (LNode *)malloc(sizeof(LNode));
		scanf("%d",&Ln_tmp2->data);//Input the data

		//Insert the data to the end odf list
		Ln_tmp1->next = Ln_tmp2;
		Ln_tmp1 = Ln_tmp2;
		Ln_tmp2->next = NULL;

	}
	return Ln_Head;
}

void ShowList(LNode *Head)
{
	LNode *P= Head->next;
	printf("The list is:\n");
	while(P)
	{
		printf("%d ",P->data);
		P = P->next;
	}
	printf("\n");
	
}

//Get the length of the List
int ListLength(LNode *Head)
{
	int length=0;
	LNode *P;
	P = Head->next;
	while(P)
	{
		length++;
		P = P->next;
	}

	return length;
}

//Get the number i data that in the list to the e parameter
//i must be >0,and <= List's length
ElemType GetElem(LNode *Head, int i, ElemType e)
{
	int j=0;
	LNode *P, *tmp;
	P = Head->next;	
	while(P && j!=i)
	{
		tmp = P;//Save the P
		P = P->next;
		j++;
	}
	return tmp->data;
}

//verify whether E is the one of list
//if return value=http://www.mamicode.com/=1,E is in the list>



链表基本操作集合