简体   繁体   中英

How to actually get the values to insert into this linked-list c++

So I wrote a function to have values insert into the linked list but now I'm having trouble successfully calling it from the main. Here's my code

 class node
 {
 public:
  int item; node* next;
  node(int x, node* t)
  {
    item = x; next = t;
  }

  void insert(int n)
  {
    node *tmp = new node(n, next);
    tmp -> item = n;
    tmp->next = head;
    head = tmp;
  }

};

typedef node *link;

int main()
{
  int i, N = 9, M = 5;
  link t = new node(1, 0); t->next = t;
  link x = t;
  for (i = 2; i <= N; i++)
   x = insert((x->next = new node(i, t)));
  while (x != x->next)
  {
    for (i = 1; i < M; i++) x = x->next;
    x->next = x->next->next;
  }
  cout << x->item << endl;
}

You could do it like this:

class Node
{
    int item; Node* next;
public:
    Node(int x, Node* t)
    {
        item = x; next = t;
    }
    int getItem() { return item; }
    Node* getNext() { return next; }
    void setNext(Node* n) { next = n; }
};

class List
{
    Node *head = nullptr;
public:
    void append(int n)
    {
        Node *tmp = new Node(n, head);
        head = tmp;
    }
    Node* getHead() { return head; }
};

int main() {
    int i, N = 9;
    List list;
    for (i = 1; i <= N; i++)
        list.append(i);
    Node* x = list.getHead();
    // remove every second element
    while (x != nullptr && x->getNext() != nullptr) {
        Node* next = x->getNext();
        x->setNext(next->getNext());
        delete next;
        x = x->getNext();
    }
    // print
    x = list.getHead();
    while (x != nullptr) {
        std::cout << x->getItem() << std::endl;
        x = x->getNext();
    }
}

This way you have List in which you can insert. And Node which stores data.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM