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