链接列表删除并返回第一个元素

时间:2013-01-16 09:34:10

标签: c list loops linked-list element

我正在尝试使用C解析shell脚本中的命令。我目前已设置链接列表,但是我无法正确删除和返回第一个元素。当我尝试获取第一个元素时,它可以正常工作一次,但之后它会卡住并进入无限循环而我不明白为什么。在此先感谢您的帮助。这是我的代码:

     enum command_type
       {
         AND_COMMAND,         // A && B
         SEQUENCE_COMMAND,    // A ; B
         OR_COMMAND,          // A || B
         PIPE_COMMAND,        // A | B
         SIMPLE_COMMAND,      // a simple command
         SUBSHELL_COMMAND,    // ( A )
       };

     // Data associated with a command.
     struct command
     {
       enum command_type type;

       // Exit status, or -1 if not known (e.g., because it has not exited yet).
       int status;

       // I/O redirections, or null if none.
       char *input;
       char *output;

       union
       {
         // for AND_COMMAND, SEQUENCE_COMMAND, OR_COMMAND, PIPE_COMMAND:
                  struct command *command[2];

         // for SIMPLE_COMMAND:
         char **word;

         // for SUBSHELL_COMMAND:
         struct command *subshell_command;
       } u;
     };

     typedef struct command_stream *command_stream_t;
     typedef struct command *command_t;

     struct command_stream
     {
        command_t command_stream;
        command_stream_t next;
     }

     command_t
     read_command_stream(command_stream_t s)
     {
        if(s)
        {
           command_t comm = s->command;
           s=s->next;
           return comm;
        }
        return NULL;
     }

     void printList(command_stream_t head)
     { 
        command_t command;
        while((command = read_command_stream(head)))
        { 
           //print_command is a function that takes in a command_t and then prints the    
           //command in a nice format.
           print_command(head->command);
        }
     }

1 个答案:

答案 0 :(得分:0)

在此函数中,您正在修改指针的本地副本(而不是您传入的主指针),因此head指针永远不会移动。

 command_t
 read_command_stream(command_stream_t s)
 {
    if(s)
    {
       command_t comm = s->command;
       s=s->next;
       return comm;
    }
    return NULL;
 }

您需要更改此函数以接受指向指针,如果您不理解这个概念,我建议您阅读一本好书(或教程)。< / p>