最近期末了,时间宝贵啊!!!高数是磨我的小妖精~~~

之前学过链表,但是没实现过,最近上C语言课开始讲链表了,所以我还是实现了一下。

链表的前提便是struct,在我的想法里,链表就是结构体的嵌套,是我们最开始的基础数据结构之一,其构成便是数据域与指针域,正因为开辟了指针域,所以链表比数组的缺点就是耗空间。

下面是单链表的实现代码,双链表期末后找时间写。

最近编译器被我玩坏了,先用C写,C++其实也一样,里面的输出语句就是我调试时的标志。

  1 #include<stdio.h>
  2 #include<stdlib.h>
  3 
  4 typedef struct node{
  5     int data;
  6     struct node *next; //C++可以不加struct 
  7 }node;
  8 
  9 node* initlist (int num){
 10     node *head = NULL;
 11     head = (node*)malloc(sizeof(struct node));
 12     head->data = num;
 13     head->next = NULL; 
 14     printf("init link-list OK!\n");
 15     return head;
 16 }
 17 
 18 
 19 void addelement(node *list,int num){
 20     node* tpre = list;
 21     while(tpre->next!=NULL)
 22         tpre = tpre->next;
 23     tpre->next = (node*)malloc(sizeof(struct node));
 24     tpre = tpre->next;
 25     tpre->data = num;
 26     tpre->next = NULL;
 27     printf("Add num:%d OK !\n",num);
 28     return ;
 29 }
 30 
 31 void delete_element(node *list,int num){
 32     node *tpre = NULL;
 33     node *tnow = list;
 34     while(tnow!=NULL){
 35         if(tnow->data==num){
 36             node *temp = tnow;
 37             tnow = tnow->next;
 38             free(temp);
 39             tpre->next = tnow;
 40             printf("delete %d OK!\n",num);
 41             return;
 42         }
 43         tpre = tnow;
 44         tnow = tnow->next;
 45     }
 46     printf("DEL Data:%d Erorr !\n",num);
 47     return ;
 48 }
 49 
 50 void changevalue(node *list,int num,int cnum){
 51     node *tnext = list;
 52     while(tnext != NULL){
 53         if(tnext->data==num){
 54             tnext->data = cnum;
 55             printf("Change data: %d to %d OK!\n",num,cnum);
 56             return;
 57         }
 58         tnext = tnext->next;
 59     }  
 60     printf("CHA Data: %d to %d Erorr !\n",num,cnum);
 61     return;
 62 }
 63 
 64 void freelinklist(node *list){
 65     node *tre = list;
 66     node *tnext = list->next;
 67     while(tnext != NULL){
 68         tnext = tnext->next;
 69         free(tre);
 70         tre = tnext; 
 71     }
 72     printf("FREE OK!\n");
 73     return ;
 74 }
 75 
 76 void showlinklist(node *list){
 77     node *tpre = list;
 78     while(tpre->next != NULL){
 79         printf("%d ",tpre->data);
 80         tpre = tpre->next;
 81     }
 82     printf("%d #\n",tpre->data);
 83     printf("Showing-Finish!\n");
 84     return ;
 85 }
 86 
 87 int main(){
 88     node *list = initlist(1);
 89     addelement(list,2);
 90     addelement(list,3);
 91     addelement(list,4);
 92     addelement(list,5);
 93     addelement(list,6);
 94     changevalue(list,6,7);
 95     changevalue(list,6,8);
 96     delete_element(list,3);
 97     delete_element(list,9);
 98     showlinklist(list);
 99     freelinklist(list);
100     return 0;
101 }
posted on 2019-12-27 00:59  白子捡一地。  阅读(189)  评论(0编辑  收藏  举报