我正在尝试使用此示例在我的函数中实现一个链表: http://www.sanfoundry.com/c-program-create-linked-list-display-elements/
滚动评论:
/** HERE. i don't want the "press 0 to exit",
* i want to take the new message from global var.
* then enter into a new node of the linked list.
**/
我的问题是我的代码实现错误,但不知道如何解决这个问题。 我认为我需要一个循环退出策略,但我在如何挣扎?
/**whenever i have a new message,
this global variable copies that message**/
char msg[30];
struct node{
char num[30];
struct node *ptr;
};
typedef struct node NODE; //call struct NODE
NODE *head, *first, *temp = 0; //initialize head, temp value to 0 and first
void function(
//if my message is available, then...
if(strlen(msg)!=0) {
while (choice){ //while true
head = (NODE *)malloc(sizeof(NODE));
//i copy the new string from the global variable declared above into
//the linked list....or that is what i am attempting to do
strcpy(head->num,msg);
printf("%s\n",s);
if (first != 0){
temp->ptr = head;
temp = head;
}
else{
first = temp = head;
}
i++;
/** HERE. i don't want the "press 0 to exit",
* i want to take the new message from global var.
* then enter into a new node of the linked list.
**/
choice=0;
}
temp->ptr = 0;
/* reset temp to the beginning */
temp = first;
while (temp != 0){
printf("%s\n", temp->num);
count++;
temp = temp -> ptr;
}
printf("No. of nodes in the list = %d\n", count);
}}
string1上的输出:
string1
新string2的输出:
string2
基本上在每个新字符串上,继续添加到链表并打印整个列表:
string1
string2
...
任何帮助。
答案 0 :(得分:1)
void function(node*head)
{
struct node* head = head;
while(NULL != head) {
printf(num);
head = head->ptr;
}
}
这将打印所有内容。把它们放进去,你需要这样的东西:
struct node* head = NULL;
void putMsg()
{
if (NULL == head)
{
head = (node *)malloc(sizeof(NODE));
temp = head;
}
else
{
temp2 = (node *)malloc(sizeof(NODE));
temp->ptr = temp2;
temp = temp->ptr;
}
char message[30];
scanf("%s", message);
strcpy(head->num, message);
}
请声明所有变量。解决方案并不精确,但至少会引导您。