双向循环链表

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

#define OK 0
#define ERROR -1

#define ElemType int

typedef struct Node
{
	ElemType data;
	Node *prev;		//指向直接前驱
	Node *next;		//指向直接后继
}Node;

//创建一个带头结点的双向循环链表
Node *createList();
//在链表的pos位置插入元素e
int insertList(Node *head, int pos, ElemType e);
//删除链表中pos位置的元素,并返回其值
int removeList(Node *head, int pos, ElemType *e);
//遍历输出整个链表
void traverse(Node *head);

int main()
{
	Node *head = createList();
	
	for (int i=1; i<=500; i++)
	{
		insertList(head, i, i);
	}
	//insertList(head, 2, 501);
	int e;
	removeList(head, 250, &e);
	printf("Remove:%d\n", e);
	traverse(head);

	system("pause");
	return 0;
}

Node *createList()
{
	Node *head = (Node *)malloc(sizeof(Node));
	if (!head)
	{
		printf("内存空间分配失败,程序将退出\n");
		exit(EXIT_FAILURE);
	}
	head->next = head->prev = head;
	return head;
}

int insertList(Node *head, int pos, ElemType e)
{
	if (!head)
	{
		printf("要插入的链表不存在\n");
		return ERROR;
	}
	Node *p = head;
	int i = 1;
	while (p->next != head && i < pos)
	{
		p = p->next;
		i++;
	}
	if (i != pos)
	{
		printf("插入失败,插入位置不正确\n");
		return ERROR;
	}

	Node *newNode = (Node *)malloc(sizeof(Node));
	if (!newNode)
	{
		printf("内存空间分配失败,程序将退出\n");
		exit(EXIT_FAILURE);
	}
	newNode->data = e;

	newNode->next = p->next;
	newNode->prev = p;
	p->next->prev = newNode;
	p->next = newNode;

	return OK;
}

int removeList(Node *head, int pos, ElemType *e)
{
	Node *p = head->next;
	int i = 1;
	while (p != head && i < pos)
	{
		p = p->next;
		i++;
	}
	if (i != pos)
	{
		printf("删除失败,删除位置有误\n");
		return ERROR;
	}
	*e = p->data;
	Node *q = p;
	p->prev->next = p->next;
	p->next->prev = p->prev;
	free(q);
	return OK;
}

void traverse(Node *head)
{
	Node *p = head->next;
	while (p != head)
	{
		printf("%d ", p->data);
		p = p->next;
	}
	printf("\n");
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值