我正试图使用此示例在函数中实现一个链表: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("%sn",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("%sn", temp->num);
count++;
temp = temp -> ptr;
}
printf("No. of nodes in the list = %dn", count);
}}
字符串1:上的输出
string1
新字符串2:上的输出
string2
基本上,在每个新字符串上,不断添加到链接列表中并打印整个列表:
string1
string2
...
请求任何帮助。
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);
}
请声明所有变量。这个解决方案并不精确,但至少会引导你。