一个简单的双端链表实现过程

//Author:Pei Chen
//Date:2017.04.30

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

typedef int ElemType;

typedef struct Node
{
	ElemType data;
	struct Node *prior;
	struct Node* next;
}Node,*DLinkList;

DLinkList DLinkListCreat()
{
	Node *L, *p, *r;
	L = (Node *)malloc(sizeof(Node));
	L->next = NULL;
	L->prior = NULL;
	r = L;
	r->next = NULL;
	r->prior = NULL;

	ElemType x;
	while ((scanf("%d", &x) != EOF)&&(x!=-1))
	{
		p = (Node *)malloc(sizeof(Node));
		p->data = x;
		p->next = r->next;
		p->prior = r;
		r->next = p;
		r = p;
	}
	r->next = NULL;
	
	return L;
}

int DLinkListFind(DLinkList L, ElemType x)
{
	DLinkList p;
	p = L->next;
	int i = 1;
	while (p!=NULL&&p->data!=x)
	{
		++i;
		p = p->next;
	}
	if (p == NULL)
		return 0;
	else
	{
		return i;
	}
}

DLinkList DLinkListInsert(DLinkList L, int i, ElemType x)
{
	DLinkList p, s,head;
	head = L;
	p = L->next;
	int tempi;
	for (tempi = 1; tempi < i - 1; tempi++)
		p = p->next;
	s = (Node *)malloc(sizeof(Node));
	s->data = x;
	s->next = p->next;
	p->next->prior = s;
	s->prior = p;
	p->next = s;

	return head;
}

DLinkList DLinkListDelete(DLinkList L, int i)
{
	int tempi = 1;
	DLinkList p,head;
	head = L;
	printf("iebfeifb00000000000000000\n");

	p = L->next;
	while ((tempi++)!=i&&p!=NULL)
	{
		p = p->next;
	}
	if (p == NULL)
		printf("位置不合法。\n");
	else if(p->next==NULL)
	{
		p->prior->next = NULL;
		p->prior = NULL;
		free(p);
	}
	else
	{
		p->prior->next = p->next;
		p->next->prior = p->prior;
		free(p);
	}
	printf("iebfeifb\n");
	return head;
}

void DLinkListPrint(DLinkList L)
{
	DLinkList temp;
	temp = L->next;
	for (; temp != NULL; temp = temp->next)
	{
		printf("%d  ", temp->data);
	}
}

int main(int argc, char* argv[])
{
	DLinkList list, start;
	list = DLinkListCreat();
	DLinkListPrint(list);
	printf("\n");

	int i;
	ElemType x;
	printf("请输入要查找的元素的值:");
	scanf("%d", &x);
	
	i = DLinkListFind(list, x);
	if (i)
		printf("在链表中的位置为:%d\n", i);
	else
	{
		printf("没有这个元素。\n");
	}
	printf("请输入插入位置:");
	scanf("%d", &i);
	printf("请输入插入元素的位置:");
	scanf("%d", &x);
	list=DLinkListInsert(list, i, x);
	DLinkListPrint(list);

	printf("\n");
	printf("请输入要删除的位置:");
	scanf("%d", &i);
	list=DLinkListDelete(list, i);
	DLinkListPrint(list);
	printf("\n");


	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值