C программа: автоматизировать один связанный список заданной длины - PullRequest
0 голосов
/ 23 марта 2020

Итак, я новичок в списке ссылок и хочу создать код, который автоматически создает один список ссылок, учитывая заголовок и размер списка. Каждый блок имеет целочисленную переменную val и указатель next. Весь код выглядит так:

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

    /* create a struct with name: mynode */
    typedef struct node{
       int val;
       struct node *next;
    } mynode;

    void populateList(mynode *head, int length){
      mynode *current, *nextblock;
      current = (mynode*)malloc(sizeof(mynode));
      nextblock = (mynode*)malloc(sizeof(mynode));

      current = head;       /* start at the head for current */

      for (int i  = 0; i < length; i++) {
        current->val = i;
        nextblock = current->next;
        current = nextblock;    
      }
      current->next = NULL;     /* for last block */
    }

/* print the list */
void printList(mynode *head){
  mynode *current = head;   /* start at the first node, which is HEAD */

  while (current != NULL) {
    printf("%d\n", current->val);
    current = current->next;    /* current is now the next block */
  }
  printf("\n");
}

int main(){

  /* local variable head points to 1st item in list */
  mynode *head = NULL;
  head = (mynode*)malloc(sizeof(mynode));

  if (head == NULL) {
    return 1;
  }
  populateList(head,5);
  printList(head);

  return 0;
}

Функция populateList - это то, что я хочу спросить. Моя логика c - переписать текущий блок и затем присвоить значение. После того, как for l oop заканчивается, текущий должен быть в последнем блоке, поэтому я назначаю указатель последнего блока, чтобы указывать на NULL. Это вызывает ошибку сегмента. Есть ли способ завершить список, используя для l oop? Пожалуйста, дайте мне знать.

Проблемная функция c заключается в следующем:

void populateList(mynode *head, int length){
      mynode *current, *nextblock;
      current = (mynode*)malloc(sizeof(mynode));
      nextblock = (mynode*)malloc(sizeof(mynode));

      current = head;       /* start at the head for current */

      for (int i  = 0; i < length; i++) {
        current->val = i;
        nextblock = current->next;
        current = nextblock;    
      }
      current->next = NULL;     /* for last block */
    }

Обновление 1

Так что я думаю, что решил проблему с ошибкой сегмента. Однако как мне вернуть этот новый связанный список, чтобы моя функция printList могла его распечатать? Это не может быть пустотой, я просто не знаю, какой будет тип функции.
С исправлением printList распечатывает только последний блок, который в данном случае равен 4, потому что я l oop из i = 0; i < 5. Ниже приведено исправление ошибки сегмента:

void populateList(mynode *head, int length){
  mynode *current = head;
  mynode *nextblock;   

  for (int i  = 0; i < length; i++) {
    current->val = i;
    nextblock = (mynode*)malloc(sizeof(mynode));
    current->next = nextblock;
    nextblock = current;
  }
  current->next = NULL;
}
...