镜花寒 2018-05-03 11:00 采纳率: 0%
浏览 975
已结题

单链表结点数据被改变

我的程序用的是单链表的头插法,插入第二个结点数据以后,第一个结点里的数据变得跟第二个结点一样了,求大神给我解释一下原理及解决办法,十分感谢!!
#include
#include
#include

#define SIZE 1024

typedef struct _node
{
char *data;
struct _node * next;
}Node;

int Insert_Head(Node h, char *data)
{
if (h == NULL)
return 0;
Node *node = (Node
)malloc(sizeof(Node)/sizeof(char));
if (node == NULL)
{
return 0;
}

node->data = data;
node->next = h->next;

h->next = node;

return 1;

}

void Display(Node *h)
{
if (h == NULL)
return;

Node *tmp = h->next;
while (tmp)
{
    printf ("%s\n", tmp->data);

    tmp = tmp->next;
}

}

int main()
{
// 创建链表
Node* head = (Node*)malloc(sizeof(Node)/sizeof(char));
if (head == NULL)
{
printf("创建链表失败\n");
return -1;
}
Node* tmp = head;
char keyword[SIZE] = {0};
char flag[10] = {0};

printf("请输入关键字1\n");
scanf("%s", keyword);
Insert_Head(head, keyword);

while(1)
{
    printf("是否还需要输入关键字?(no or yes)\n");
    scanf("%s", flag);
    if(!strcmp(flag, "yes"))
    {
        memset(keyword, 0, SIZE);
        printf("请输入关键字:\n");
        scanf("%s", keyword);
        Insert_Head(head, keyword);
        memset(flag, 0, 10);
    }
    else
    {
        memset(flag, 0, 10);
        break;
    }
}

Display(head);

return 0;

}

  • 写回答

4条回答 默认 最新

  • 叫码农就行 2018-05-03 11:16
    关注

    你的那个插入操作有问题,改成下面这样应该没问题了
    int Insert_Head(Node *h, char *data)
    {
    if (h == NULL)
    return 0;
    Node *node = (Node)malloc(sizeof(Node)/sizeof(char));
    if (node == NULL)
    {
    return 0;
    }

    node->data = data;
    node->next = h;//把新建的节点插入到头部,即他的next指向头节点

    h = node;//把头节点指向新的头节点,即新插入的节点

    return 1;
    }

    评论

报告相同问题?

悬赏问题

  • ¥15 ELGamal和paillier计算效率谁快?
  • ¥15 file converter 转换格式失败 报错 Error marking filters as finished,如何解决?
  • ¥15 ubuntu系统下挂载磁盘上执行./提示权限不够
  • ¥15 Arcgis相交分析无法绘制一个或多个图形
  • ¥15 关于#r语言#的问题:差异分析前数据准备,报错Error in data[, sampleName1] : subscript out of bounds请问怎么解决呀以下是全部代码:
  • ¥15 seatunnel-web使用SQL组件时候后台报错,无法找到表格
  • ¥15 fpga自动售货机数码管(相关搜索:数字时钟)
  • ¥15 用前端向数据库插入数据,通过debug发现数据能走到后端,但是放行之后就会提示错误
  • ¥30 3天&7天&&15天&销量如何统计同一行
  • ¥30 帮我写一段可以读取LD2450数据并计算距离的Arduino代码