问题
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:
- In
print_list, you may want to changeprintf(" %s\n",ptr->val);toprintf(" %c\n",ptr->val);if you want to print the value at the node as a character. - I don't know why you are incrementing
posbefore using it. You probably meant to increment it after the linecreate_list(storage[pos]);. - The argument type to
create_listis anint. You are passing achar *to it. Perhaps you meant to passstorage[pos][0]. - You probably also meant
tok = strtok(tok, " ");. Otherwise, thewhileloop 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