zoukankan      html  css  js  c++  java
  • 链表存储从文件读取的数据

     1 #include"getWhitelist_demo.h"
     2 
     3 void Initialize_List(List *l)
     4 {
     5     *l=(List)malloc(sizeof(Node));
     6     (*l)->Next=NULL;
     7 }
     8 
     9 void Insert(ElemType X,List L)
    10 {
    11     List TmpCell,P=L;
    12     TmpCell = (List)malloc(sizeof(Node));
    13     TmpCell->Element=(ElemType)malloc(strlen(X)*sizeof(*X));///0001
    14     if(TmpCell==NULL)
    15         return 0;
    16     ///TmpCell->Element=X;error0011
    17     strcpy(TmpCell->Element,X);///0002
    18     TmpCell->Next=NULL;
    19     while(P->Next!=NULL)
    20         P=P->Next;
    21     P->Next=TmpCell;
    22     return 1;
    23 }
    24 
    25 List GetLists(const char* file)
    26 {
    27     List lst,P;
    28     Initialize_List(&lst);
    29     FILE * fp;
    30     char buf[1024];
    31     fp=fopen(file,"rw+");
    32     if(!fp)
    33         perror("file:");
    34     while(fgets(buf,1023,fp)!=NULL)
    35     {
    36         Insert(buf,lst);
    37     }
    38     return lst;
    39 }
    40 
    41 void printout(List llst)
    42 {
    43     Position P;
    44     P=llst->Next;
    45     while(P!= NULL)
    46     {
    47         printf("Element: %s",P->Element);
    48         P=P->Next;
    49     }
    50 }
    View Code
     1 #ifndef GETLISTS_DEMO
     2 #define GETLISTS_DEMO
     3 
     4 #include<stdio.h>
     5 #include<string.h>
     6 
     7 typedef char* ElemType;
     8 
     9 typedef struct Node Node;
    10 typedef struct Node* List;
    11 typedef List Position;
    12 struct Node
    13 {
    14     ElemType Element;
    15     List Next;
    16 };
    17 
    18 #endif // GETLISTS_DEMO
    View Code

    今天犯了一个错误,在第一段代码里面是error0001的错误,这里只是“重复性的将指向文件读取的那个字符数组的地址”,这样导致每次将链表打印的时候总是最后一个值。

    将error0001换成0001、0002两行之后,问题解决了,因为这样真正的是将所有文件读取的值存储到了链表而不只是重复性的去复制指针地址(而且是一个指针地址)。

  • 相关阅读:
    underscore.js,jquery.js源码阅读
    css3动画知识点
    ajax防止重复提交
    jquery data属性的使用
    文字换行
    vue的生命周期
    iphone与安卓的兼容性问题汇总
    python 上下文管理器
    form 校验
    常用的字段和字段参数
  • 原文地址:https://www.cnblogs.com/bibaodi/p/4707261.html
Copyright © 2011-2022 走看看