1

所以我有这个链接列表,它可以工作,但前提是你将一个项目添加到列表中。这是我的代码:

    struct node{
       char key[10];
       char content[20];
       struct node *next;
    };
    struct node *head=(struct node *) NULL;
    struct node *tail=(struct node *) NULL;

    struct node * initinode(char *key, char *content)
    {
     struct node *ptr;
     ptr = (struct node *) malloc(sizeof(struct node ) );
      if( ptr == NULL )                       
         return (struct node *) NULL;        
      else {                                  
         strcpy( ptr->key, key );          
         strcpy(ptr->content,content);                       
           return ptr;                         
           }
     }
    void printnode( struct node *ptr )
    {
      printf("Key ->%s\n", ptr->key );
      printf("Contents   ->%d\n", ptr->content );
     }
    void printlist( struct node *ptr )
      {
         while( ptr != NULL )           
         {
           printnode( ptr );          
           ptr = ptr->next;            
         }
     }
    void add( struct node *new )  
    {
       if( head == NULL ) {     
         head = new;
         tail=new; 
       }                   
       else {
         tail->next = new;        
         tail->next=NULL;              

            }
    }

因此,当我尝试将三个项目添加到列表并打印时,它只会显示第一个项目,例如这三个:

     struct node *ptr;
    char *terminal="term";
        char *term;
        term=getenv("TERM");  
      ptr=initinode(terminal, term);
          add(ptr);
     //-----------------------
      char ccterm[20];
      char *ret, tty[40];
      char *currTerminal="tty";
     if ((ret = ttyname(STDIN_FILENO)) == NULL)
               perror("ttyname() error");
     else {
        strcpy(tty, ret); 
          }
      ptr=initinode(currTerminal, tty);
      add(ptr);

    //----------------------------------
     char cwd[1024];
     char *st="date";
     time_t t;
     char ti[30];
     time(&t);
     char date;
     date=t;
     sprintf(ti,"%s", ctime(&t));
     ptr=initinode(st, ti);
     add(ptr);
     printlist(ptr);

这让我想到了最后一个问题,当我将其中任何一个添加到列表时,它只输出 int 值,那么我将如何打印列表中的字符串值。我曾尝试将我的代码修改为男性内容字符串,但它永远不会成功。非常感谢任何建议,谢谢

4

3 回答 3

2

在你的 add 函数中,你有这个:

tail->next = new;        
tail->next=NULL;

什么时候应该

tail->next = new;
tail = new;
tail->next=NULL;

另一个问题是在 printnode 中。打印内容时,您应该使用 %s 作为字符串。%d 用于整数。

于 2013-02-27T04:46:29.093 回答
0

要打印字符串,您需要修复您的printnode函数。

printf("Contents   ->%s\n", ptr->content );
                      ^

它打印int值是因为您专门要求它(%d)打印int值。

Justin 已经解决了您的 add 函数的另一个问题。

于 2013-02-27T04:47:31.003 回答
0
  1. 不要施放malloc()NULL

  2. 程序中的问题:

    tail->next = new; //I am new list
    tail->next=NULL; //I am nobody!

你可能的意思是:

tail->next = new;
tail->next->next = NULL;
tail = tail->next;
于 2013-02-27T04:49:24.650 回答