Adding Char Value to a Linked List using Looping [C]

≡放荡痞女 提交于 2019-12-11 16:47:42

问题


I have a linked list which Im currently trying to add values to it. But I must have set my pointers incorrectly or there is something going on with the memory allocation.

I want to add tokens to the list but everytime there is a new loop the data overlaps. For example:

1st time:

repl> a a

2nd time:

repl> b b

b

Notice how the a just disappears, I want to keep the previous values while adding in new values.

Here's my code so far:

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

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

struct node* create_list (int 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 (int 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;
}

struct exp {
    int type;
    union {
        int num;
        char name;
        double decimal;
        char strq;
    } value;
};


int main(int argc, char *argv[])
{
    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++;
            storage[pos] = tok;
            create_list(storage[pos]);
            tok = strtok(NULL," ");
        }

        print_list();
    }
}

回答1:


I see the following problems in your code:

  1. In print_list, you may want to change printf(" %s\n",ptr->val); to printf(" %c\n",ptr->val); if you want to print the value at the node as a character.
  2. I don't know why you are incrementing pos before using it. You probably meant to increment it after the line create_list(storage[pos]);.
  3. The argument type to create_list is an int. You are passing a char * to it. Perhaps you meant to pass storage[pos][0].
  4. You probably also meant tok = strtok(tok, " ");. Otherwise, the while loop is not doing you any good.

After I made those changes to your code in my computer, the program behaved like you expected it o.



来源:https://stackoverflow.com/questions/22124297/adding-char-value-to-a-linked-list-using-looping-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!