链表(c语言实现)

节点的数据结构

struct Node
{
    int value;
    struct Node* next;
};
typedef struct Node Node;

操作和演示

#include <stdlib.h>
#include <stdio.h>
// 建立一个节点 Node *createNode(int value) { Node *pNode = (Node *) malloc(sizeof(Node)); pNode->value = value; pNode->next = NULL; return pNode; } // 建立一个空链表(带头节点) Node *createList() { return createNode(-0x3f3f3f); } // 删除一个节点 void deleteNode(Node *list, int index) { Node *temp = list->next; Node *node = NULL; int count = 1; index -= 1; if (index == 0) { node = list->next; list->next = list->next->next; free(node); return; } while (temp != NULL && count < index) { temp = temp->next; count++; } list = temp; node = list->next; list->next = temp->next->next; // 从链表中摘除 free(node); } // 销毁链表 void destroy(Node *list) { Node *temp = list->next; Node *node = NULL; int count = 1; while (temp != NULL) { node = temp; temp = temp->next; free(node); } free(list); } // 在指定的位置插入一个节点 void insert(Node *list, Node *node, int index) { Node *temp = list->next; int count = 1; index -= 1; if (index == 0) { list->next = node; node->next = temp; return; } while (temp != NULL && count < index) { temp = temp->next; count++; } list = temp; temp = temp->next; list->next = node; node->next = temp; } // 在末尾追加一个节点 void append(Node *list, Node *node) { Node *temp = list->next; if (temp == NULL) { list->next = node; return; } while (temp->next != NULL) temp = temp->next; temp->next = node; } // 显示链表 void showList(Node *list) { Node *temp = list->next; if (list == NULL || temp == NULL) { printf("null\n"); return; } printf("%d", temp->value); temp = temp->next; while (temp != NULL) { printf("->%d", temp->value); temp = temp->next; } printf("\n"); } // 得到一个节点 Node *getNode(Node *list, int index) { Node *temp = list->next; int count = 1; while (temp != NULL && count < index) { temp = temp->next; count++; } return count == index ? temp : NULL; } int main() { Node *list = createList(); Node *pNode = NULL; int i; for (i = 1; i <= 3; i++) { pNode = createNode(i * 10); append(list, pNode); } showList(list); deleteNode(list, 1); showList(list); pNode = createNode(40); insert(list, pNode, 1); showList(list); pNode = getNode(list, 1); printf("%d\n", pNode->value); destroy(list); return 0; }

猜你喜欢

转载自www.cnblogs.com/li1234567980/p/13401486.html