[英]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. 这样,您就可以在其中插入
List
。 And Node
which stores data. 还有存储数据的
Node
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.