单链表(双指针)
#include <stdio.h> #include <stdlib.h> #include <time.h> typedef struct Node{ int value; struct Node *pNext; } Node;
/* 打印链表 */
void show_data(Node *head) { if (head == NULL) { return; } Node* cur = head; while (cur) { printf("%d ", cur->value); cur = cur->pNext; } printf("\n"); }
/* 创建链表 */ Node* creatNode_New(int data) { Node* new = (Node*)malloc(sizeof(Node)); new->value = data; new->pNext = NULL; return new; }
/* 反转链表 */ Node* revertNode(Node* head) { Node* cur = head; Node* next = NULL; while (cur != NULL) { Node* tmp = cur; cur = cur->pNext; tmp->pNext = next; next = tmp; } return next; }
/* 插入链表_表头 */ void insertNode_Front(Node** head, Node* new) { if (head == NULL) { *head = new; } else { new->pNext = *head; *head = new; } }
/* 插入链表_表尾 */ void insertNode_Back(Node** head, Node* new) { if (head == NULL) { *head = new; } else { Node* tmp = *head; while (tmp->pNext != NULL) { tmp = tmp->pNext; } tmp->pNext = new; } }
/* 统计链表长度 */ int GetNodeSize(Node* head) { if (head == NULL) { return 0; } int size = 0; Node* cur = head; while (cur) { size++; cur = cur->pNext; } printf("size:%d\n", size); return size; }
/* 删除链表_表头 */ void deleteNode_Front(Node** head) { if (*head == NULL) { return; } else { if ((*head)->pNext == NULL) { free(*head); *head = NULL; } else { Node* cur = *head; *head = (*head)->pNext; free(cur); } } }
/* 删除链表_表尾 */ void deleteNode_Back(Node** head) { if (*head == NULL) { return; } else { if ((*head)->pNext == NULL) { free(*head); *head = NULL; } else { Node* cur = *head; Node* pre = NULL; while (cur->pNext) { pre = cur; cur = cur->pNext; } free(cur); pre->pNext = NULL; } } }
/* 清空链表 */
void cleanNodeList(Node** head) { Node* cur = *head; while (cur) { Node* tmp = cur; cur = cur->pNext; free(tmp); } *head = NULL; } int main(void) { Node* head = NULL; Node* revNode = NULL; for (int i = 1; i < 10; i++) { insertNode_Front(&head, creatNode_New(i)); } GetNodeSize(head); show_data(head); revNode = revertNode(head); show_data(revNode); deleteNode_Front(&revNode); show_data(revNode); deleteNode_Back(&revNode); show_data(revNode); cleanNodeList(&revNode); show_data(revNode); return 0; }