2014-10-31 76 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