我想在下面的代码中保留链表的开头。我不认为我的代码有任何问题,但是当我添加两个节点并调用print时,它会显示第二个节点的名字。
编辑:现在不显示任何内容!它是空的
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>
struct node {
char Number[10];
char FirstName[10];
char LastName[10];
char FatherName[10];
char Email[20];
char SiteName[30];
struct node *next;
};
void print( struct node* list)
{
printf("print1");
printf(list->FirstName);
printf("print2");
}
void addNode(struct node *head)
{
struct node *current = head;
puts("*******Now you can insert a new person****");
struct node *newNode = malloc(sizeof(struct node));
printf("FIRSTNAME: ");
gets(newNode->FirstName);
printf("LASTNAME: ");
gets(newNode->LastName);
printf("FATHERNAME: ");
gets(newNode->FatherName);
printf("EMAIL: ");
gets(newNode->Email);
printf("SITENAME: ");
gets(newNode->SiteName);
//create new node
newNode->next = 0; // Change 1
//check for first insertion
if(current->next == 0){
current->next = newNode;
printf("added at beginning\n");
}
else
{
//else loop through the list and find the last
//node, insert next to it
while (current->next != 0) {
current = current->next;
}
current->next = newNode;
printf("added later\n");
}
}
//*************************************************************************
int main()
{
/* This won't change, or we would lose the list in memory */
struct node *root;
/* This will point to each node as it traverses the list */
struct node *conductor;
root = malloc( sizeof(struct node) );
root->next = 0;
addNode(root);
addNode(root);
conductor = root;
//*********************************
print(root);
if ( conductor != 0 ) {
while ( conductor->next != 0)
{
conductor = conductor->next;
}
}
/* Creates a node at the end of the list */
conductor->next = malloc( sizeof(struct node) );
conductor = conductor->next;
if ( conductor == 0 )
{
printf( "Out of memory" );
return 0;
}
/* initialize the new memory */
conductor = root;
if ( conductor != 0 ) {
/* Makes sure there is a place to start */
while ( conductor->next != 0 ) {
puts( conductor->FirstName );
puts( conductor->LastName );
conductor = conductor->next;
}
puts( conductor->FirstName );
}
return 0;
}发布于 2011-12-26 05:18:40
gets(current->FirstName);current指向与head相同的struct node,头节点被传递给addNode。因此,您将覆盖传递给addNode的struct node的值,而不是使用上面的代码创建的新节点。
我假设您应该将名字、姓氏等存储在newNode和指向的节点中,而不是 current。
通过使用gets,您的代码也容易受到缓冲区溢出的影响;请考虑使用fgets。我还希望FirstName、LastName等被定义为char[],而不是char*,这样它们就会有内存分配给它们,以便存储字符串。
发布于 2011-12-26 05:18:16
编辑:您的打印函数现在不输出任何内容,因为根节点为空。下面是你的列表:
+------+ +------------------+ +-------------------+
| root | ---> | first user entry | ---> | second user entry |
+------+ +------------------+ +-------------------+所以,如果你替换掉
print(root);使用
print(root->next);它将打印用户输入的第一个条目。
旧答案:在这一行中:
gets(current->FirstName);用新值覆盖current->FirstName的值。由于current指向head,因此您将覆盖第一个节点的值。
要解决此问题,请先对新节点执行malloc操作,然后将值gets到其中( newNode中,而不是current中)。不要忘记为newNode->FirstName和其他字段分配足够的空间,否则gets会溢出您的缓冲区。事实上,please don't use gets at all。
https://stackoverflow.com/questions/8631593
复制相似问题