双向循环链表

#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");
}

发布了33 篇原创文章 · 获赞 10 · 访问量 5万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章