單向列表節點node
typedef struct Node { int data; struct Node *next; } LinkNode;
單鏈表建立 反轉鏈表 刪除節點ui
//建立節點 LinkNode *rootNode = malloc(sizeof(LinkNode)); rootNode->data = 1; rootNode->next = NULL; LinkNode *node1 = malloc(sizeof(LinkNode)); node1->data = 2; node1->next = NULL; LinkNode *node2 = malloc(sizeof(LinkNode)); node2->data = 3; node2->next = NULL; //生成鏈表 rootNode->next = node1; node1->next = node2; //反轉鏈表 LinkNode *node = reverseLink(rootNode); //刪除鏈表中的值爲3元素 deleteLinkElement(node, 2);
反轉鏈表spa
LinkNode* reverseLink(LinkNode *node){ if (node == NULL) {return NULL;} LinkNode *pre = NULL; while (node) { LinkNode *nextTemp = node->next; node->next = pre; pre = node; node = nextTemp; } return pre; }
刪除鏈表節點code
LinkNode* deleteLinkElement(LinkNode *node, int element) { if (node == NULL) {return NULL;} LinkNode *pre = NULL; while (node) { LinkNode *nextTemp = node->next; if (node->data == element) { if (pre) { pre->next = nextTemp; } else { *node = *nextTemp; } } pre = node; node = nextTemp; } return pre; }