양 방향 링크 의 응용

2162 단어 데이터 구조
#include
#include
#include

typedef char DataType;
typedef struct Node
{
	DataType data;
	struct Node *prior;
	struct Node *next;
}DListNode,*DLinkList;
DListNode* GetElem(DLinkList head, int i);
void PrintDList(DLinkList head);
int CreateDList(DLinkList head, int n);
int InsertDList(DLinkList henad, int i, char e);

int InitDList(DLinkList *head)
{
	*head = (DLinkList)malloc(sizeof(DListNode));
	if (!head)
		return -1;
	(*head)->next = *head;  //     prior next      
	(*head)->prior = *head;
	return 1;
}
int CreateDList(DLinkList head, int n)
{
	DListNode *s, *q;
	int i;
	DataType e;
	q = head;
	for (i = 1; i <= n; i++)
	{
		printf("  %d   ", i);
		e = getchar();
		s = (DListNode*)malloc(sizeof(DListNode));
		s->data = e;//               
		s->next = q->next;
		q->next = s;
		s->prior = q;
		head->prior = s;//        prior        
		q = s;  //q          
		getchar();
	}
	return 1;
}
int InsertDList(DLinkList head, int i, DataType e)
{
	DListNode *p, *s;
	p = GetElem(head, i);		//      i   
	if (!p)
		return 0;
	s = (DListNode*)malloc(sizeof(DListNode));
	if (!s)
		return -1;
	s->data = e;		// s          
	s->prior = p->prior;
	p->prior->next = s;
	s->next = p;
	p->prior = s;
	return 1;
}

DListNode* GetElem(DLinkList head ,int i)
{
	DListNode *p;
	int j;
	p = head->next;
	j = 1;
	while (p != head && j < i)
	{
		p=p->next;
		j++;
	}
	if (p == head || j>i)   //       ,  NULL
		return NULL;
	return p;
}
void main()
{
	DLinkList h;
	int n, pos;
	char e;
	InitDList(&h);
	printf("      :");
	scanf("%d", &n);
	getchar();
	CreateDList(h, n);
	printf("      :");
	PrintDList(h);
	printf("         :");
	scanf("%c", &e);
	getchar();
	scanf("%d", &pos);
	InsertDList(h, pos, e);
	printf("           :");
	PrintDList(h);
}
void PrintDList(DLinkList head)  //              
{
	DListNode *p;
	p = head->next;
	while (p != head)
	{
		printf("%c", p->data);
		p = p->next;
	}
	printf("
"); }

좋은 웹페이지 즐겨찾기