编写算法实现建立一个带头结点的含n个元素的双向循环链表H,并在链表H中的第i个位置插入一个元素e

头文件:函数的声明

#include 
#include 
#include 

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

int InitDList(DLinkList *head);
DListNode *GetElem(DLinkList head,int i);
void PrintDList(DLinkList head);
int CreateDList(DLinkList head,int n);
int InsertDList(DLinkList head,int i,ElemType e);


函数的定义

#include "双向链表.h"

int InitDList(DLinkList *head)
{
	*head = (DLinkList)malloc(sizeof(DListNode));
	if(!head)
	{
		return -1;
	}
	(*head)->next = *head;
	(*head)->prior = *head;
	return 1;
}
DListNode *GetElem(DLinkList head,int i)
{
	DListNode *p;
	int j = 1;
	p = head->next;
	while(p != head && j < i)
	{
		p = p->next ;
		j++;
	}
	if(p == head || j > i)
	{
		return NULL;
	}
	return p;
}

void PrintDList(DLinkList head)
{
	DListNode *p;
	p = head->next;
	while(p != head)
	{
		printf("%c",p->data);
		p = p->next;
	}
	printf("\n");
}

int CreateDList(DLinkList head,int n)
{
	DListNode *s,*q;
	int i;
	ElemType e;
	q = head;
	for(i = 1;i <= n;i++)
	{
		printf("请输入第%d个元素",i);
		e = getchar();
		s = (DLinkList)malloc(sizeof(DListNode));
		s->data = e;
		s->next = q->next;
		q->next = s;
		s->prior = q;
		head->prior = s;
		q = s;
		getchar();
	}
	return 1;
}

int InsertDList(DLinkList head,int i,ElemType e)
{
	DListNode *p,*s;
	p = GetElem(head,i);
	if(!p)
	{
		return 0;
	}
	s = (DLinkList)malloc(sizeof(DListNode));
	if(!s)
	{
		return -1;
	}
	s->data = e;
	s->prior = p->prior ;
	p->prior ->next = s;
	s->next = p;
	p->prior = s;
	return 1;
}


函数的应用

#include "双向链表.h"

int main(void)
{
	DLinkList h;
	int n,pos;
	ElemType e;
	InitDList(&h);
	printf("请输入元素的个数:");
	scanf("%d",&n);
	getchar();
	CreateDList(h,n);
	printf("链表中的元素:");
	PrintDList(h);
	printf("请输入插入元素:");
	scanf("%c",&e);
	printf("请输入插入元素的位置:");
	scanf("%d",&pos);
	InsertDList(h,pos,e);
	printf("插入元素后链表中的元素:");
	PrintDList(h);
	return 0;
}


你可能感兴趣的:(C语言)