线性链表的操作(查找、插入、删除、销毁)

#include
#include

typedef int elemtype;
typedef struct LNode
{
	elemtype data;
	elemtype len;
	struct LNode *next;
}LNode, *Linklist; 

Linklist Initlist()//初始化线性表 
{
	Linklist head;
	head=(Linklist)malloc(sizeof(LNode));
	head->next=NULL; 
	head->len=0; 
	return head;
}

//Linklist Insertlist(Linklist head, elemtype n)
void Createlist(Linklist head, elemtype n)//尾插法建立线性表 
{
	Linklist p,r;
	r=head;
	for(elemtype i=0;idata);
      	r->next=p;
		r=p;
		head->len++;     
      }
      r->next=NULL; 
      //return p;
}

elemtype Search(Linklist head,elemtype e)//查找元素 
{
	Linklist p;
	elemtype n=0; 
	p=head;
	while(p->next!=NULL)
	{
        if(p->data==e)break;	
		p=p->next;
		n++; 
	}
	if(p->data==e)printf("Found! The pos is at %d !\n",n);
	else printf("Not Found!\n"); 
	return n;
}

void Insert(Linklist head,elemtype n,elemtype e)//插入元素 
{ 
	Linklist p;
	p=(Linklist)malloc(sizeof(LNode));  
	if(n>(head->len))printf("error");
	else 
	{  
	    for (int i = 0; i < n - 1; i++)head = head->next;
		p->data = e;
		p->next = head->next;
		head->next = p;
		head->len++;
	}
}

void Delete(Linklist head,elemtype e)//删除元素e 
{
	Linklist s,p; 
	elemtype n=0; 
	p=head;
	while(p->next!=NULL)
	{
        if(p->data==e)break;	
		p=p->next;
		n++; 
	}
	for(elemtype i=0;inext;
	s=head->next;
	head->next=s->next; 
	free(s);
	head->len--; 
}

void print(Linklist head)//打印 
{
	Linklist p;
	p=head->next;
	while(p!=NULL)
	{
		printf("%d ",p->data);
		p=p->next; 
	}
	printf("\n");
}

void Destory(Linklist head)//销毁线性表 
{
	Linklist s;
	while(head->len>0)
	{
	   s=head->next;
	   head->next=s->next; 
	   free(s);
	   head->len--; 
    }
    printf("Destory!\n");
}

int main()
{
	Linklist head;
	head=Initlist();
	elemtype n;
	printf("输入元素个数n:\n");
	scanf("%d",&n);
	Createlist(head,n);
	Search(head,10);
	Insert(head,3,9);
	Delete(head,10);
	print(head);
	Destory(head);
}

输入:

8

1 2 3 4 10 6 7 8

运行结果如下:

线性链表的操作(查找、插入、删除、销毁)_第1张图片

你可能感兴趣的:(数据结构,c语言,线性表)