自己写的单链表操作

来源:互联网 发布:普那路亚群婚知乎 编辑:程序博客网 时间:2024/04/30 16:25
#include <stdio.h>#include <string.h>#include <stdlib.h>#define NODE_SIZE sizeof(Node)typedef struct _tagNode{int value;struct _tagNode *next;}Node;Node* createlink(Node *cur){Node* pn = NULL;pn = (Node*)malloc(NODE_SIZE);pn->value = 0;pn->next = NULL;if (cur->value == 0){return pn;}pn->value = cur->value;return pn;}Node* insertnode2tail(Node *head,Node *node){//尾部插入Node *cur = head;Node *pn = NULL;if (node->value == 0){return head;}pn = (Node*)malloc(NODE_SIZE);pn->value = node->value;pn->next = NULL;while (cur->next != NULL){cur = cur->next;}cur->next = pn;return head;}Node* insertnode2head(Node *head,Node *node){//头部插入Node *newhead = NULL;if (node->value == 0){return head;}newhead = (Node*)malloc(NODE_SIZE);newhead->value = node->value;newhead->next = head;return newhead;}Node* insertnode(Node *head,Node *node){//找到合适位置插入Node *cur = head;Node *pn = NULL;Node *prov = head;if (node->value == 0){return head;}pn = (Node*)malloc(NODE_SIZE);pn->value = node->value;if (cur->value >= node->value){head = insertnode2head(head,pn);}else{while (cur->value < node->value){prov = cur;cur = cur->next;}prov->next = pn;pn->next = cur;}return head;}Node* deletenode(Node *head,Node *del){Node *cur = head;Node *prov = head;if (cur->value == del->value){//如果删除的是头指针Node *phead = cur->next;free(cur);cur = NULL;return phead;}while (cur->value != del->value){prov = cur;cur = cur->next;}prov->next = cur->next;free(cur);cur = NULL;return head;}void printlink(Node *head){Node *tmp = head;while (tmp->next != NULL){printf("%d ",tmp->value);tmp = tmp->next;}printf("%d ",tmp->value);}void deletelink(Node *head){Node *cur = head;Node *prov = head;while (cur->next != NULL){prov = cur;cur = cur->next;free(prov);}free(cur);cur = NULL;prov = NULL;}int main(void){Node tmp;Node *head = NULL;int i = 0;tmp.value = 2;head = createlink(&tmp);for (i =2; i <= 10; ++i){tmp.value = i*2;head = insertnode2tail(head,&tmp);}printlink(head);putchar('\n');tmp.value = 13;head = insertnode(head,&tmp);printlink(head);putchar('\n');tmp.value = 1;head = insertnode(head,&tmp);printlink(head);putchar('\n');return 0;}


 

0 0