-2

In Header File:

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

typedef struct myStruct myStruct;

Relative Function:

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

So I think that's pretty straightforward. Any help would be appreciated.

4

2 回答 2

3

You can do something like this.

// 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;
}
于 2013-10-03T04:01:22.237 回答
0

Inside that for loop you should somehow create the nodes you need (probably asking the user for input and using malloc() as you say), and then link from the previous one. In this case you would want to keep a pointer to the last element of the list, as that would be the one that would point to the new one when it gets linked.

An academic-but-functional implementation of this can be found in this project at my University.

于 2013-10-03T03:37:40.717 回答