【问题标题】:LinkedList entering strings into nodes and printing list?LinkedList 将字符串输入节点并打印列表?
【发布时间】:2014-10-31 13:05:39
【问题描述】:

我正在尝试使用此示例在我的函数中实现链表: 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("%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);



    }}

string1 上的输出:

 string1

在新字符串 2 上输出:

 string2

基本上在每个新字符串上,不断添加到链表并打印整个列表:

 string1
 string2
 ...

寻求任何帮助。

【问题讨论】:

  • 很多代码丢失了。请提供MCVE
  • 我的实际代码太长了,所以我说msg(glob var.)每次都会复制新的字符串。
  • @user3035890 不要使用全局变量。重写没有全局变量的代码。
  • 请提供main函数的代码
  • @VladfromMoscow 我有另一个生成字符串的函数,我将这些字符串复制到全局变量中

标签: c string loops while-loop linked-list


【解决方案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--> 没有node *,它要么是NODE *,要么是struct node *。 2-->不要强制转换malloc()的返回值。
  • 在 Microsoft Visual Studio 中必须进行强制转换,因为它返回 void*。在其他地方,对错误感到抱歉。我现在正在做一个插件。
猜你喜欢
  • 1970-01-01
  • 2020-07-01
  • 1970-01-01
  • 2023-03-25
  • 1970-01-01
  • 2023-01-07
  • 1970-01-01
  • 2017-04-02
  • 1970-01-01
相关资源
最近更新 更多