#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");
}
雙向循環鏈表
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.