单循环链表(带头结点、头节点数据域为节点数)
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node* next;
}Node;
Node* initLoopLinkList() {
Node* list = (Node*)malloc(sizeof(Node));
list->data = 0;
list->next = list;
return list;
}
void headPush(Node* list,int data) {
Node* n = (Node*)malloc(sizeof(Node));
n->data = data;
n->next = list->next;
list->next = n;
list->data++;
}
void tailPush(Node* list, int data) {
Node* n = (Node*)malloc(sizeof(Node));
n->data = data;
n->next = list;
Node* temp = list;
for (int i = 0; i < list->data; i++) {
temp = temp->next;
}
temp->next = n;
list->data++;
}
int delete(Node* list,int data) {
Node* pre = list;
Node* cur = list->next;
while (cur != list) {
if (cur->data == data) {
pre->next = cur->next;
free(cur);
list->data--;
return 1;
}
else {
pre = cur;
cur = cur->next;
}
}
return 1;
}
void print(Node* list) {
Node* temp = list;
while (temp->next != list) {
printf("%d ", temp->next->data);
temp = temp->next;
}
printf("\n");
}
void test() {
Node* list = initLoopLinkList();
headPush(list, 5);
headPush(list, 6);
headPush(list, 7);
print(list);
tailPush(list, 1);
tailPush(list, 3);
tailPush(list, 2);
print(list);
delete(list, 3);
print(list);
delete(list, 6);
print(list);
}
int main() {
test();
return 0;
}