我想用这个例子来实现我的功能一个LinkedList: http://www.sanfoundry.com/c-program-create-linked-list-display-elements/LinkedList将字符串输入到节点和打印列表中?
向下滚动到评论:
/** 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);
}}
输出的字符串1:
string1
输出新的字符串2:
string2
基本上在每一个新的字符串,不断加入到链表和打印整个列表:
string1
string2
...
appecia任何帮助。
很多代码缺失。请提供[MCVE](http://stackoverflow.com/help/mcve)。 – 2014-10-31 13:07:23
我的实际代码太长,所以我说msg(glob var。)每次都会复制新的字符串。 – user3035890 2014-10-31 13:09:38
@ user3035890请勿使用全局变量。重写没有全局变量的代码。 – 2014-10-31 13:11:44