如何实际获取值插入此链接列表C ++

时间:2018-10-05 05:15:53

标签: c++ linked-list

所以我写了一个函数来将值插入到链表中,但是现在我很难从主函数成功调用它。这是我的代码

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

1 个答案:

答案 0 :(得分:0)

您可以这样做:

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

这样,您可以插入List。还有Node,它存储数据。