【问题标题】:Dynamically Create Linked List in C在 C 中动态创建链表
【发布时间】:2013-10-09 14:12:55
【问题描述】:

在头文件中:

struct myStruct{
  int data;
  struct myStruct *next;
};

typedef struct myStruct myStruct;

相对函数:

myStruct * create(){
  myStruct * a = NULL;
  int size;
  printf("Enter Size of List : ");
  scanf("%d",&size);

  for(int i = 0;i<size;i++){
  /*
   * can't seem to figure out how to do this correctly.
   * 
   * I know I have to use malloc(sizeof()),etc..
   *
   * I've only had success with creating the list backwards.
   * 
   * In this loop there would be a scan from user input for 
   *      the data instance
   */
  }
return a;
}

所以我认为这很简单。任何帮助将不胜感激。

【问题讨论】:

  • 这个 'myStruct a = NULL' 是否编译?如果是这样,我很惊讶。
  • 对不起,我是凭记忆做的(不是复制粘贴)。 'a' 是一个指针...已编辑
  • 在您的循环中,向用户询问号码。用 malloc 分配一个 myStruct 并将数据字段设置为来自用户的数字。跟踪列表中的最新项目并使用它来设置下一个指针。然后将最近的项目设置为您刚刚分配的项目。祝你好运。
  • 有道理(开始实施)...感谢您的帮助
  • 另一种可能性是向后创建列表,然后在完成后将其反转。这种技术在函数式语言中很常见,在创建列表节点后不允许对其进行变异。

标签: c dynamic linked-list


【解决方案1】:

你可以这样做。

// Get user input and store it in the list
void getValue(myStruct *ptr)
{
    printf("\nEnter Data:");
    scanf("%d",&ptr->data);
    ptr->next=NULL;
}

myStruct * create()
{
   myStruct * a_head = NULL;  // start of list
   myStruct * a_tail = NULL;  // end of list
   int size,i;
   printf("Enter Size of List : ");
   scanf("%d",&size);

   for(i=0;i<size;i++)
   {
      // Creating first node
      if(i==0)
      {
         a_head=a_tail=malloc(sizeof(myStruct));
         getValue(a_tail);
      }
      // Creating other nodes
      else
      {
         a_tail->next=malloc(sizeof(myStruct)); // adding new node to the end of non-empty list
         getValue(a_tail->next); // Insert data into the new node
         a_tail=a_tail->next; // update tail pointer
      }
   }
return a_head;
}

【讨论】:

  • 这个的主要问题是它不能优雅地处理早期的 EOF。否则,它看起来是正确的——我会保留尾部指针(以及头部指针),以便在尾部添加也很容易。
【解决方案2】:

for 循环中,您应该以某种方式创建您需要的节点(可能要求用户输入并使用malloc(),如您所说),然后从前一个链接。在这种情况下,您需要保留一个指向列表最后一个元素的指针,因为它会在链接时指向新元素。

可以在 this project at my University 中找到一个学术但功能性的实现。

【讨论】:

    猜你喜欢
    • 2016-07-28
    • 2016-07-10
    • 2011-10-25
    • 2018-08-27
    • 2015-12-31
    • 1970-01-01
    • 1970-01-01
    • 2017-10-11
    • 2011-01-19
    相关资源
    最近更新 更多