我想用這個例子來實現我的功能一個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