Обзор этой связанной программы списка - PullRequest
1 голос
/ 27 мая 2019

Это программа в связанном списке, которая печатает данный ввод. Но возможно ли это сделать без использования оператора if(start==NULL) ...else ..?

#include <stdio.h>
#include <malloc.h>
struct node
{
    int data;
    struct node* next;
}* start = NULL;

void main()
{
    struct node* tmp;
    struct node *ptr, *tmp1;

    int n = 0;
    int choice = 2;

    while (1)
    {
        printf("Enter a number less than 3 to continue");
        scanf("%d", &choice);
        if (choice >= 3)
            break;

        printf("Enter the input");
        scanf("%d", &n);
        // n=n+10;
        if (start == NULL)
        {
            tmp = (struct node*)malloc(sizeof(struct node));
            start = tmp;
            start->data = n;
            ptr = start;
        }
        else
        {
            tmp = (struct node*)malloc(sizeof(struct node));
            ptr->next = tmp;
            tmp->data = n;
            ptr = tmp;
        }
    }
    tmp->next = NULL;


    printf("\nThe output of the linked list is\n");
    n = 0;
    ptr = start;
    while (ptr != NULL)
    {
        printf("\n  1 ptr =           %d", ptr->data);
        ptr = ptr->next;
    }
}

Ответы [ 3 ]

1 голос
/ 27 мая 2019

Переменная start содержит заголовок связанного списка.

Условие if (start == NULL) проверяет наличие пустого списка.

Если список пуст, вам нужно создать заголовок списка. Начиная со второго элемента, вам нужно связать следующий элемент с последним элементом списка. Об этом заботится условие else.

Если посмотреть по-другому, если у вас нет условия if, у вас есть строка

 ptr->next = tmp;

Поскольку ptr не инициализируется в это время, вы будете иметь неопределенное поведение и, скорее всего, получите ошибку сегментации.

1 голос
/ 27 мая 2019

возможно ли это сделать без использования оператора if (start == NULL) ... else ..?

Да

Создать головной узели используйте только его .next член.

#include <stdio.h>
#include <malloc.h>

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

int main(void) {
  struct node head = {.next = NULL};  // only need .next 
  struct node *ptr = &head;

  while (1) {
    // ...

    int n;
    printf("Enter the input ");
    fflush(stdout);
    if (scanf("%d", &n) != 1) {
      break;
    }
    ptr->next = malloc(sizeof *ptr->next);
    if (ptr->next == NULL) {
      break;
    }
    ptr = ptr->next;
    ptr->data = n;
    ptr->next = NULL;
  }

  printf("\nThe output of the linked list is\n");
  ptr = head.next; // The start of the list is here
  while (ptr) {
    printf("  1 ptr =           %d\n", ptr->data);
    ptr = ptr->next;
  }
}
0 голосов
/ 27 мая 2019

Ну, многого не нужно.

Вы можете просто определить узел как

struct node 
{
    int data;
    node * next; // Will hold the value of next node's address
};

Теперь вы можете просто создать класс структуры данных с помощью методов.

class LinkedList {
  private:
    node *head, *current, *temp; // 3 Main pointers
  public:

    LinkedList() {
      head = temp = current = NULL; // Set them to NULL
    }

    void insert(int data) { // to add a new node
      if(head == NULL) { // if there is no node in the memory
        head = new node; // use head to make a new node
        head->data = data; // set the data of the node to data
        head->next = NULL; // set the next to NULL
        temp = current = head; // 3 pointers sitting at the head node
      }
      else { // If the node is not the first one in the memory
        current = new node; // use current pointer to make new node
        temp->next = current; // temp pointer one step behind the current node
        current->next = NULL; // make the next of new node NULL
        temp = current; // move the pointer to current
        current->data = data;
      }
    }
};

Эта функция будет просто добавлять узлы при каждом вызове.

Чтобы отобразить список, просто переместите временный указатель на заголовок и запустите итерацию

void display()
{
    temp = head; // move to head
    while(temp != NULL) // while temp doesn't reach the end
    {
        cout<<temp->data<< " "; // print the node's data
        temp = temp->next; // move the pointer to next node
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...