手撕链表(自存)
#include<stdio.h> #include<stdlib.h> typedef int E; typedef struct node { E val; struct node* next; }ListNode; ListNode* list_creat() { ListNode* list = malloc(sizeof(ListNode)); return list; } void push_back(ListNode* List, E val) { if (!List) { printf("List is NULL!"); exit(1); } ListNode* p = malloc(sizeof(ListNode)); if (!p) { printf("error"); exit(1); } p->val = val; p->next = NULL;//尾插法,新元素next为空 ListNode* tail = List; while (tail->next) { tail = tail->next; } tail->next = p; } void push_front(ListNode** List, E val) { ListNode* p = malloc(sizeof(ListNode)); if (!p) { printf("error"); exit(1); } p->val = val; p->next = *List; *List = p; } E pop_back(ListNode *List) { if (List == NULL) { printf("error"); exit(1); } ListNode* pre, * curr; pre = NULL; curr = List; while (curr) { pre = curr; curr = curr->next; } E value = curr->val; free(curr); pre->next = NULL; return value; } E pop_front(ListNode** List) { E value = (*List)->val; ListNode* p = malloc(sizeof(ListNode)); p = *List; *List = p->next; free(p); return value; } void destroy_list(ListNode* List) { ListNode* curr, * next; curr = List; while (curr) { next = curr->next; free(curr); curr = next; } free(List); }
int main(void) {
ListNode* list = list_creat();
push_back(list, 1);
push_back(list, 4);
push_back(list, 8);
push_back(list, 9);
add_before_head(&list, 10);
return 0;
}