双向链表的学习

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

#define SLEN (sizeof(struct STU))

typedef struct STU
{
	int a;
	struct STU *pre;
	struct STU *nxt;		
}*DListNode;

/*
	创建双向链表 
*/
DListNode create(int a)
{
	DListNode head=(DListNode)malloc(SLEN);	
	head->a=a;
	head->pre=NULL;
	head->nxt=NULL;
	return head;
} 

/*
	查找要插入的位置
	既然查询的时间复杂度都是O(n) 
*/
DListNode find(DListNode h,int a)
{
	DListNode p=h;
	if(h==NULL)
	{
		printf("Error:链表不能为空\n");
		return NULL;
	}
	while(p->nxt!=NULL&&p->nxt->a!=a)
	{
		p=p->nxt;
	}
	return p;
}

/*
	双向链表的插入 
*/
int insertElement(DListNode h,int a)
{
	DListNode p;
	DListNode temp;
	DListNode newL;
	if(h==NULL)
	{
		printf("Error:表头为空\n");
		return 0;
	}
	p=find(h,a);
	temp=p->nxt;
	newL=(DListNode)malloc(SLEN);
	if(newL==NULL)
	{
		printf("Error:申请内存失败\n");
		return 0;
	}
	if(temp!=NULL)
	temp->pre=newL;
	newL->a=a;
	newL->pre=p;
	newL->nxt=temp;
	p->nxt=newL;
	return 1;
}

/*
	循环打印出双向链表 
*/
void printfList(DListNode h)
{
	DListNode p=h;
	if(h==NULL)
	{
		printf("链表不能为空\n");
	}
	while(p!=NULL)
	{
		printf("%d \n",p->a);
		p=p->nxt;
	}	
}

/*
	删除链表元素 
*/
int deleteElement(DListNode h,int a)
{
	DListNode p=find(h,a);
	DListNode t;
	if(p==NULL)
	{
		return 0;
	} 
	if(p->nxt==NULL)
	{
		printf("链表中无此元素\n");
		return 0; 
	}
	if(p->nxt->nxt!=NULL)
	{
		t=p->nxt->nxt;
		t->pre=p;
	}
	else
	{
		t=NULL;
	}
	free(p->nxt);
	p->nxt=t;
	return 1;
} 

int main(void)
{
	DListNode t;
	DListNode n=create(10);
	insertElement(n,1);
	insertElement(n,2);
	insertElement(n,3);
	insertElement(n,4);
	insertElement(n,5);
	deleteElement(n,5);
	printfList(n);
	while(n!=NULL)
	{
	 	t=n->nxt;
		free(n);		
		n=t;
	}
	deleteThisList(n);
	printfList(n); 
}

  

posted on 2017-01-23 16:32  HelloWorldTotti  阅读(288)  评论(1编辑  收藏  举报

导航