单链表插入或删除元素

在单链表按大小顺序插入或删除元素

在这里插入图片描述

//按元素大小顺序插入到链表中
#include
#include
#includestruct Node
{int value;struct Node *next;
};void insertNode(struct Node **head,int value)
{struct Node *previous;struct Node *current;struct Node *new;current = *head;previous = NULL;while(current!=NULL&¤t->value < value){previous = current;		//previous记录current上一个节点的位置current = current ->next;}new = (struct Node *)malloc(sizeof(struct Node));if(new == NULL){printf("内存分配失败!");exit(1);}new ->value = value;new ->next = current;if(previous == NULL){*head = new;}else{previous ->next = new;}
}void printNode(struct Node *head)
{struct Node *current;current = head;while(current != NULL){printf("%d ",current->value);current = current ->next;}printf("\n");
}void deleteNode(struct Node **head,int value)
{struct Node *previous;struct Node *current;current = *head;previous = NULL;while(current != NULL && current->value != value){previous = current;current = current->next;}if(current == NULL){printf("找不到匹配的节点\n");return;}else{if(previous == NULL){*head = current ->next;}else{previous ->next = current->next;}free(current);}
}
int main(void)
{struct Node *head = NULL;int input;printf("开始测试插入整数...\n");while(1){printf("\n请输入一个整数(-1表示结束):");scanf("%d",&input);printf("\n"); if(input == -1){break;}insertNode(&head,input);printNode(head);}printf("开始测试删除整数...\n");while(1){printf("\n请输入一个整数(-1表示结束):");scanf("%d",&input);printf("\n"); if(input == -1){break;}deleteNode(&head,input);printNode(head);}return 0;
}

演示结果:

在这里插入图片描述


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部