C++ creation of linked lists of data structures

  • 2020-05-30 20:52:51
  • OfStack

C++ creation of linked lists of data structures

preface

1. Linked lists are used very frequently in C/C++ because it is so used that it ACTS as a natural mutable array. push does not affect the previous list items until the end.

2. Generally, when creating a linked list, a member variable such as next points to the next item, and the list is created by defining 1 head and last, with the reference function TestLinkCreateStupid().

instructions

linus says that TestLinkCreateClever() does not use Pointers at all (I really do not know how to use Pointers). This method does not need to judge at all in the loop, so it can be seen how efficient it is.


// test_shared.cpp :  Define the entry point for the console application. 
//

#include "stdafx.h"
#include <memory>
#include <string>
#include <iostream>

typedef struct stage_tag {
  int         data_ready;   /* Data present */
  long        data;      /* Data to process */
  struct stage_tag  *next;     /* Next stage */
} stage_t;

//  Efficient way to create linked lists 
stage_t* TestLinkCreateClever(int stages)
{
  stage_t *head = NULL,*new_stage = NULL,*tail = NULL;
  stage_t **link = &head; //  The difference is in this pointer address variable , It ACTS as a binding new stage The role of .
  for(int i =0; i<stages;++i)
  {
    new_stage = (stage_t*)malloc(sizeof(stage_t));   
    new_stage->data_ready = 0;
    new_stage->data = i;

    *link = new_stage; //  The new stage Assigned to link The address of the pointer to 
    link = &new_stage->next; //  Under the binding 1 Pointer address of 
  }

  tail = new_stage;
  *link = NULL;

  return head;
}

//  An inefficient way to create lists 
stage_t* TestLinkCreateStupid(int stages)
{
  stage_t *head = NULL,*new_stage = NULL,*tail = NULL;
  for(int i =0; i<stages;++i)
  {
    new_stage = (stage_t*)malloc(sizeof(stage_t));   
    new_stage->data_ready = 0;
    new_stage->data = i;
    new_stage->next = NULL;

    if(tail)
      tail->next = new_stage;
    else
      head = new_stage;

    tail = new_stage;
  }
  return head;
}

int _tmain(int argc, _TCHAR* argv[])
{
  std::cout << "=== TestLinkCreateClever ===" << std::endl;
  auto first = TestLinkCreateClever(10);
  while(first)
  {
    std::cout << "data: " << first->data << std::endl;
    first = first->next;
  }

  std::cout << "=== TestLinkCreateStupid ===" << std::endl;
  auto second = TestLinkCreateStupid(10);
  while(second)
  {
    std::cout << "data: " << second->data << std::endl;
    second = second->next;
  }
  return 0;
}


If you have any questions, please leave a message or come to the site community to exchange discussion, thank you for reading, hope to help you, thank you for your support of the site!


Related articles: