在C中动态创建链接列表

时间:2013-10-03 02:14:15

标签: c dynamic linked-list

在标题文件中:

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

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

2 个答案:

答案 0 :(得分:2)

你可以这样做。

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

答案 1 :(得分:0)

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

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