在链接列表的开头插入字符串时出错 [英] Error inserting string at the beginning of a Linked List

查看:43
本文介绍了在链接列表的开头插入字符串时出错的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试编写一个程序,该程序将一个字符串插入到链表的开头,但是其中存在一个小问题.我的代码如下.

I have been trying to write a program which inserts a string into the beginning of the linked list, however there has been a slight problem in it. My code is the following.

#include <stdio.h>
#include <stdlib.h>

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



void insIni(struct node** hp, char* x){
    struct node* tmp = (struct node *)malloc(sizeof(struct node)); 
    tmp->data = x;
    tmp->next = *hp;
    *hp = tmp;
}

void printList(struct node* h){
    struct node* tmp = h;
    printf("\nList contents: \n");
    while (tmp != NULL){
        printf("%s,  ", tmp->data );
        tmp = tmp->next;
    }
    printf("\n");
}

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

    struct node* head = NULL;  

     char word [256];
     scanf("%s", word);  
    insIni(&head, word);
    scanf("%s", word);  
    insIni(&head, word);
    scanf("%s", word);  
    insIni(&head, word);

    printList(head);

    return 0;
}

在链接列表的开头插入新字符串后,先前的元素也更改为与刚刚插入的字符串相同,如何更改代码,以便链接的先前元素列表保持不变,只添加开头的元素?

After I insert a new string at the beginning of the linked list, the previous elements are also changed to be the same as the string that has just been insterted, how can I change my code so that the previous elements of the linked list stay the same and only the element at the beginning is added?

例如,如果我写A B C,则链接列表最终将打印为C,C,C,而不是C,B,A....

For example, if I write A B C, the Linked List ends up being printed as C, C, C, instead of C, B, A,.

推荐答案

您传递给insIni的值始终相同,因此所有节点都指向相同的值.您需要做的是复制数据.

The value you pass to insIni is always the same so all nodes will point to the same. What you need to do is a copy of the data.

例如

void insIni(struct node** hp, char* x){
    struct node* tmp = (struct node *)malloc(sizeof(struct node)); 
    tmp->data = strdup(x);
    tmp->next = *hp;
    *hp = tmp;
}

char *p = malloc(strlen(x)+1);
strcpy(p, x);
tmp->data = p;

这篇关于在链接列表的开头插入字符串时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆