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