首页 > 其他 > 详细

单链表插入与删除数据

时间:2019-09-11 11:53:22      阅读:96      评论:0      收藏:0      [点我收藏+]

 

  1 //按元素大小顺序插入到链表中
  2 #include<stdio.h>
  3 #include<stdlib.h>
  4 #include<string.h>
  5 
  6 struct Node
  7 {
  8     int value;
  9     struct Node *next;
 10 };
 11 
 12 void insertNode(struct Node **head, int value)
 13 {
 14     struct Node *previous;
 15     struct Node *current;
 16     struct Node *newnode;
 17 
 18     current = *head;
 19     previous = NULL;
 20     
 21     
 22     while (current != NULL && current->value < value)
 23     {
 24         int b = current->value;
 25         previous = current;        //previous记录current上一个节点的位置
 26         current = current->next;
 27     }
 28     newnode = (struct Node *)malloc(sizeof(struct Node));//分配内存
 29     if (newnode == NULL)
 30     {
 31         printf("内存分配失败!");
 32         exit(1);
 33     }
 34     newnode->value = value;
 35     newnode->next = current;
 36     if (previous == NULL)
 37     {
 38         *head = newnode;
 39     }
 40     else
 41     {
 42         previous->next = newnode;
 43     }
 44     
 45 }
 46 
 47 void printNode(struct Node *head)
 48 {
 49     struct Node *current;
 50     current = head;
 51     while (current != NULL)
 52     {
 53         printf("%d ", current->value);
 54         current = current->next;
 55     }
 56     printf("\n");
 57 }
 58 
 59 void deleteNode(struct Node **head, int value)
 60 {
 61     struct Node *previous;
 62     struct Node *current;
 63 
 64     current = *head;
 65     previous = NULL;
 66 
 67     while (current != NULL && current->value != value)
 68     {
 69         previous = current;
 70         current = current->next;
 71     }
 72     if (current == NULL)
 73     {
 74         printf("找不到匹配的节点\n");
 75         return;
 76     }
 77     else
 78     {
 79         if (previous == NULL)
 80         {
 81             *head = current->next;
 82         }
 83         else
 84         {
 85             previous->next = current->next;
 86         }
 87         free(current);
 88     }
 89 }
 90 int main()
 91 {
 92     struct Node *head = NULL;
 93     int input;
 94     printf("开始测试插入整数...\n");
 95     while (1)
 96     {
 97         printf("\n请输入一个整数(-1表示结束):");
 98         scanf("%d", &input);
 99         printf("\n");
100         if (input == -1)
101         {
102             break;
103         }
104         insertNode(&head, input);
105         printNode(head);
106     }
107 
108     printf("开始测试删除整数...\n");
109     while (1)
110     {
111         printf("\n请输入一个整数(-1表示结束):");
112         scanf("%d", &input);
113         printf("\n");
114         if (input == -1)
115         {
116             break;
117         }
118         deleteNode(&head, input);
119         printNode(head);
120     }
121 
122     return 0;
123 }

转载自:khq溪风

 

单链表插入与删除数据

原文:https://www.cnblogs.com/hsy1941/p/11505172.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!