相比单链表加了一个尾结点指向头结点
#include <stdio.h>
#include <stdlib.h>
typedef struct Node{
int data;
struct Node* next;
}Node;
Node* list_init()
{
Node* L = (Node*)malloc(sizeof(Node));
L->next = L;
L->data = 0;
return L;
}
int head_insert(Node* L,int data)
{
Node* node = (Node*)malloc(sizeof(Node));
node->next = L->next;
node->data = data;
L->next = node;
L->data++;
return 0;
}
void printf_node(Node* L)
{
Node* current = L;
current = current->next;
while(current != L)
{
printf("%d\t",current->data);
current = current->next;
}
printf("\n");
printf("num = %d\n",L->data);
}
int delete_node(Node* L,int data)
{
Node* pre = L;
Node* current = L->next;
while(current != L)
{
if(current->data == data)
{
pre->next = current->next;
free(current);
L->data--;
return 0;
}
pre = current;
current = current->next;
}
return -1;
}
int main(int argc, char const *argv[])
{
Node* L = list_init();
head_insert(L,3);
head_insert(L,4);
head_insert(L,5);
head_insert(L,6);
head_insert(L,7);
delete_node(L,5);
printf_node(L);
return 0;
}