循环双链表-增添元素

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

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

DLinkList insertTailElem(DLinkList &L)
{
	L = (DLinkList)malloc(sizeof(LDNode));
	LDNode *r,*s;
	r = L;
	ElemType x;
	scanf("%d",&x);
	while(x!=9999)
	{
		s = (LDNode*)malloc(sizeof(LDNode));
		s->data = x;
		r->next = s;
		s->prior = r;
		r = s;
		scanf("%d",&x);
	}
	r->next = L;
	L->prior = r;
	return L;
}

//循环双链表-在第i位置上增加元素x
bool insertElem(DLinkList &L,int i,ElemType x)
{
	LDNode *s,*p=L;
	int j=0;
	while(p->next!=L&&j<i-1)
	{
		p = p->next;
		++j;
	}
	if(j==i-1)
	{
		s = (LDNode*)malloc(sizeof(LDNode));
		s->data = x;
		s->next = p->next;
		p->next->prior = s;
		p->next = s;
		s->prior = p;
		return true;
	}
	else
		return false;
}

void printList(DLinkList L)
{
	LDNode *p = L->next;
	while(p!=L)
	{
		printf("%d ",p->data);
		p = p->next;
	}
	printf("\n");
}	

void main()
{
	DLinkList L;
	insertTailElem(L);
	printList(L);
	insertElem(L,2,30);
	printf("在第2位上添加元素30:\n");
	printList(L);
}

上一篇:王道C语言短期班——week1总结


下一篇:星空智能对话机器人的Gavin认为Transformer是拥抱数据不确定性的艺术