获取链接列表中的上一个值

时间:2014-03-03 00:09:36

标签: c linked-list

我有一个链接列表,它接收用户输入的标记值并将它们存储在列表中。我希望能够访问存储的先前值。

例如:

if (tok = "add") 
{
//Get the previous 2 stored elements in the linked list and add them
}

到目前为止,这是我的代码:

        #include <stdio.h>
    #include <conio.h>
    #include <string.h>
    #include <stdlib.h>
    #include <stdbool.h>
    #include <ctype.h>



    struct node {
        char *val;
        struct node *next;
        };

    struct node *head = NULL;
    struct node *cur = NULL;

    struct node* create_list (char *value) {
        struct node *ptr = (struct node*) malloc(sizeof (struct node));
        if (NULL == ptr) return NULL;
        ptr->val = value;
        ptr->next = NULL;

        ptr->next = head;
        head = ptr;

        return ptr;
        };

    struct node* insertion (char *value) {
        if (NULL == head)
            return (create_list(value));

        struct node *ptr = (struct node*)malloc(sizeof(struct node));
        ptr->val = value;
        ptr->next = NULL;

        ptr->next = head;
        head = ptr;

    return ptr;

    };

void print_list(void)
{
    struct node *ptr = head;

    while(ptr != NULL)
    {
        printf(" %s\n",ptr->val);
        ptr = ptr->next;
    }

    return;
}


void destroy_list(void)
{
  struct node *ptr = head;
  struct node *tmp = NULL;

  while(ptr != NULL) {
    free(ptr->val);
    tmp = ptr;
    ptr = ptr->next;
    free(tmp);
  }
}

struct exp
{
    int type;
    union
    {
        char strq[50];
        } myvalue;
    };


    int main(int argc, char *argv[])  {

        struct exp in;


        while(1)
        {
            printf("repl>");
            char *storage [30];
            char* tok;
            char g;
            char buffer[20];
            int pos = 0, i;
            fgets(buffer,sizeof(buffer),stdin);

            tok = strtok(buffer," ");

            while (tok)
        {
                pos++;
                if(pos >= 30)
                {
                    goto _exit_left;
                }
                        storage[pos] = strdup(tok);

                        strcpy(in.myvalue.strq, tok);
                        if(isdigit(in.myvalue.strq))
                        {
                            create_list (strdup(in.myvalue.strq));
                        }
                        create_list(strdup(in.myvalue.strq));


                tok = strtok(NULL," ");
        }
        print_list();
        }
        _exit_left:
            destroy_list();
    }

1 个答案:

答案 0 :(得分:0)

使用带有2个指针的链接列表。一个指向您在代码中已经拥有的下一个节点,另一个指向指向前一个节点的指针。