Ich habe ein paar Stunden verbringen diese Lösung, aber ich denke, es wäre besser, wenn mir jemand dabei helfen könnte:Warum speichert diese benutzerdefinierte verknüpfte Liste nicht jedes in C++ angegebene Element?
struct node{
int x;
node *next;
}; // basic node struct
class LinkedList{
private:
node *head;
public:
LinkedList(int init){ // initalizating the list
head = new node;
node *rot = new node;
rot->next = 0;
rot->x = init;
head->x = -1;
head->next = rot;
cout << "added: " << head->next->x << endl;
}
void add(int adds){
if(head != 0) {
while (head->next){ // goes to the latest head
head = head->next;
}
}
node *rot = new node;
rot->next = 0;
rot->x = adds;
head->next = rot;
cout << "added: " << head->next->x << endl;
}
int push_last() { // pushes the last element, works fine
node *temp = head;
while(temp->next)
temp = temp->next;
return temp->x;
}
int push_first(){ //shows the penultimate element instead of first one
return head->x;
}
};
int main()
{
LinkedList lt(1);
lt.add(2);
lt.add(3);
lt.add(4);
cout << lt.push_first() << endl; // prints 3/the penultimate element each time
cout << lt.push_last() << endl; // prints last element always(4 in this case)
return 0;
}
ich das nicht will wie meine Hausaufgaben suchen, weil es wirklich isn t. Ich habe versucht, es für ein paar Stunden herauszufinden, es viel zu ändern, danke für jede Hilfe!
Edit: es neu geschrieben:
class LinkedList{
private:
node *head;
public:
LinkedList(int init){ head = new node;
head->next = nullptr;
head->x = init;
}
void add(int toadd){
node *tnode = head;
while(tnode->next!= nullptr){
tnode = tnode->next;
}
tnode->next = new node;
tnode->next->x = toadd;
tnode->next->next = nullptr;
}
void print(){
node *tmp = head;
while(tmp->next!=nullptr){
cout << tmp->x << endl;
tmp = tmp->next;
}
cout << tmp->x << endl;
}
};
int main()
{
LinkedList lt(1);
lt.add(3);
lt.add(62);
lt.add(123);
lt.add(9521);
lt.print();
return 0;
}
Was haben Sie beobachtet, wenn durch den Code Schritt den Debugger? –
Soll in der 'add'-Funktion wirklich geändert werden, wo die Member-Variable' head' zeigt? Dadurch verlieren Sie den ursprünglichen Kopf. –
Beachten Sie, dass 'push' normalerweise ** ** etwas zu einem Container hinzufügt, also ist' push_first' ein eigentümlicher Name. –