带头结点非循环双向链表

#include"stdio.h"
#include"malloc.h"

typedef struct DNode
{
	int data;
	DNode *prior, *next;
}DNode;

void InitDNode(DNode *&p)
{
	p = (DNode *)malloc(sizeof(DNode));
	p->prior = NULL;
	p->next = p;
}

void createDNode(DNode *p)
{
	int n;
	DNode *r,*q;
	r = p;
	printf("Input data, input -1 to end: ");
	scanf("%d",&n);
	while(n != -1)
	{
		q = (DNode *)malloc(sizeof(DNode));
		q->next = q->prior = NULL;
		q->data = n;
		r->next = q;
		q->prior = r;
		r = q;
		scanf("%d",&n);
	}
}

void display(DNode *p)
{
	DNode *r;
	r = p->next;
	printf("The List: ");
	while(r != NULL)
	{
		printf("%d  ",r->data);
		r = r->next;
	}
	printf("\n");

}

int lengthDNode(DNode *p)
{
	DNode *r;
	int n = 0;
	r = p->next;
	while(r->next != NULL)
	{
		++n;
		r = r->next;
	}
	return n;

}

int InsertDNode(DNode *p, int position, int x)
{
	if(position<=0 || position >lengthDNode(p)+1)
	{
		printf("The position is not suitable!\n");
		return 0;
	}
	DNode *q, *r;
	q = (DNode *)malloc(sizeof(DNode));
	q->data = x;
	q->next=q->prior = NULL;
	int n = 1;
	r = p->next;
	while(n!= position-1)
	{
		r = r->next;
		++n;
	}
	q->prior = r;
	q->next = r->next;
	r->next->prior = q;
	r->next = q;
	return 1;
}

void InvertDisplay(DNode *p)
{
	DNode *r;
	r = p->next;
	while(r->next != NULL)
	{
		r = r->next;
	}
	printf("InverseList: ");
	while(r->prior!=NULL)
	{	
		printf("%d  ",r->data);
		r = r->prior;
	}
	printf("\n");
}

int DeleteDNode(DNode *p, int position, int &x)
{
	DNode *r,*q;
	if(position<=0 || position> lengthDNode(p)+1)
	{
		printf("The position is not suitable!\n");
		x = -1;
		return 0;
	}
	r = p->next;
	int n=1;
	while(n != position-1)
	{
		r = r->next;
		++n;
	}
	q = r->next;
	x = q->data;
	r->next = q->next;
	q->next->prior = r;
	free(q);
	return 1;
}

void main()
{
	DNode *p;
	InitDNode(p);
	createDNode(p);
	display(p);
	InsertDNode(p,2,9);
	display(p);
	InvertDisplay(p);
	int x;
	DeleteDNode(p,2,x);
	printf("The delete DNode is %d\n",x);
	display(p);
}

你可能感兴趣的:(c)