单链表C纯C语言代码实现
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node* next;
}Node;
Node* initSingleLinkList(){
Node* list = (Node*)malloc(sizeof(Node));
list->data = 0;
list->next = NULL;
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* temp = list;
for (int i = 0; i < list->data; i++) {
temp = temp->next;
}
Node* n = (Node*)malloc(sizeof(Node));
n->data = data;
n->next = NULL;
temp->next = n;
list->data++;
}
void headPop(Node* list) {
if (list->data == 0) {
return;
}
else {
Node* temp = list->next;
list->next = temp->next;
free(temp);
list->data--;
}
}
void tailPop(Node* list) {
if (list->next == NULL) {
return;
}
else {
Node* temp = list;
for (int i = 0; i < list->data-1; i++) {
if (temp->next != NULL) {
temp = temp->next;
}
}
free(temp->next);
temp->next = NULL;
list->data--;
}
}
void print(Node* list) {
while (list->next != NULL) {
printf("%d ", list->next->data);
list = list->next;
}
printf("\n");
}
void test() {
Node* list = initSingleLinkList();
headPush(list, 1);
headPush(list, 2);
headPush(list, 3);
headPush(list, 4);
print(list);
tailPush(list, 5);
tailPush(list, 6);
tailPush(list, 7);
print(list);
headPop(list);
print(list);
tailPop(list);
print(list);
}
int main(){
test();
return 0;
}