2014-10-31 70 views
0

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

+0

很多代碼缺失。請提供[MCVE](http://stackoverflow.com/help/mcve)。 – 2014-10-31 13:07:23

+0

我的實際代碼太長,所以我說msg(glob var。)每次都會複製新的字符串。 – user3035890 2014-10-31 13:09:38

+0

@ user3035890請勿使用全局變量。重寫沒有全局變量的代碼。 – 2014-10-31 13:11:44

回答

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); 
} 

請聲明所有的變量。解決方案並不精確,但至少會導航您。

+1

1 - >沒有'node *',它的'NODE *'或'struct node *'。 2 - >不要施加'malloc()'的返回值。 – 2014-10-31 13:41:00

+0

在Microsoft Visual Studio中,它是必須的,因爲它返回void *。在其他地方,對於錯誤感到抱歉。我現在正在做一個插件。 – celeborn 2014-10-31 13:45:31