有头节点的双向循环链表
#include <stdio.h>
#include <stdlib.h>
typedef struct Node
{
int data;
struct Node *pre;
struct Node *next;
} Node;
Node *initList()
{
Node *DoubleLoopLink = (Node *)malloc(sizeof(Node));
if (DoubleLoopLink == NULL)
{
printf("malloc DoubleLoopLink error!\n");
}
DoubleLoopLink->data = 0;
DoubleLoopLink->pre = DoubleLoopLink;
DoubleLoopLink->next = DoubleLoopLink;
return DoubleLoopLink;
}
void headInsert(Node *DoubleLoopLink, int data)
{
Node *newNode = (Node *)malloc(sizeof(Node));
if (newNode == NULL)
{
printf("malloc newNode error!\n");
}
newNode->data = data;
// 链表为空
if (DoubleLoopLink->data == 0)
{
newNode->pre = DoubleLoopLink;
newNode->next = DoubleLoopLink->next;
DoubleLoopLink->next = newNode;
DoubleLoopLink->pre = newNode;
}
else // 链表不为空
{
newNode->next = DoubleLoopLink->next;
newNode->pre = DoubleLoopLink;
DoubleLoopLink->next->pre = newNode;
DoubleLoopLink->next = newNode;
}
DoubleLoopLink->data++;
}
void tailInsert(Node *DoubleLoopLink, int data)
{
Node *newNode = (Node *)malloc(sizeof(Node));
if (newNode == NULL)
{
printf("malloc newNode error!\n");
}
newNode->data = data;
Node *current = DoubleLoopLink;
while (current->next != DoubleLoopLink)
{
current = current->next;
}
newNode->pre = current;
newNode->next = DoubleLoopLink;
DoubleLoopLink->pre = newNode;
current->next = newNode;
DoubleLoopLink->data++;
}
void printList(Node *DoubleLoopLink)
{
Node *head = DoubleLoopLink;
Node *current = DoubleLoopLink->next;
while (current != head)
{
printf("%-5d", current->data);
current = current->next;
}
printf("\n");
printf("剩余 %d 个节点\n", DoubleLoopLink->data);
}
void delete(Node *DoubleLoopLink, int data)
{
Node *current = DoubleLoopLink->next;
while (current != DoubleLoopLink)
{
if (current->data == data)
{
current->pre->next = current->next;
current->next->pre = current->pre;
free(current);
DoubleLoopLink->data--;
return;
}
current = current->next;
}
}
int main(int argc, char const *argv[])
{
Node *DoubleLoopLink = initList();
for (int i = 0; i <= 100; i++)
{
tailInsert(DoubleLoopLink, i);
}
delete (DoubleLoopLink, 100);
delete (DoubleLoopLink, 0);
delete (DoubleLoopLink, 50);
printList(DoubleLoopLink);
return 0;
}