如何在C中改进此链表,使其没有无限循环?

问题描述

我正在查看一些旧代码,在scanf函数之后无法进入打印语句。每次我运行此代码时,都必须使用控件c中断它。我对链接列表缺少什么帮助我解决此问题?就上下文而言,我已经很久没有上过C语言课程了,我想回顾一下如何正确使用链表之类的数据结构,但是由于某种原因,我几年前做过的这个问题使我难以理解。我该怎么办?

#include <stdio.h>
#include <stdlib.h>

void trav_and_print(void);

typedef struct linked_list
{
   int data;
   struct linked_list *next;
}   element;
int a;
int* pA = &a;
typedef element * elementptr;
  elementptr first = NULL,last = NULL,current;
            

int main()
{
   /* Create a linked list with one element            */
   /* NOTE: the first element is always a special case */
   
   first = (elementptr) malloc(sizeof(element));
   last = first;
   last -> data = 5;
   last -> next = NULL;

   /* Add another element to the end of the list */

   last -> next = (elementptr) malloc(sizeof(element));
   last = last -> next;
   last -> data = 12;
   last -> next = NULL;
   printf("%d \n",last->data);

   last -> next = (elementptr) malloc(sizeof(element));
   last = last -> next;
   printf("Enter a number: ");
   scanf("%d\n",pA);
   fflush(stdin); 
   last -> next = (elementptr) malloc(sizeof(element));
   last = last -> next;
   last -> data = a;
   last -> next = NULL;
   printf("Number added is %d \n",last -> data);

   trav_and_print();
   free(first);
   free(last);

   return 0;
}

void trav_and_print(void)
{

   current = first;
   while (current!=NULL)
   {
      printf("The data value is %d\n",current -> data);
      current = current -> next;
   }
}

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)