【发布时间】:2021-07-23 19:22:24
【问题描述】:
我是数据结构的新手。我终于掌握了在链表开头添加新元素的窍门 但现在还有另一个问题。我已经观看了很多 YouTube 视频,但问题仍未解决。我试图在这个链表的末尾添加一个元素,但是当我这样做时,前两个元素消失了。请帮忙!
#include <iostream>
using namespace std;
class Node{
public:
int data;
Node *next;
Node(){
data = 0;
next = NULL;
}
};
Node* add_end(Node* a, int new_data){
Node* ptr, *temp;
ptr = a;
temp = new Node();
temp->data = new_data;
temp->next = NULL;
while(ptr->next != NULL) {
ptr = ptr->next;
}
ptr->next = temp;
return ptr;
}
void print(Node* a){
while(a != NULL){
cout << a->data << " ";
a = a->next;
}
}
int main(){
Node *head = NULL;
Node *second = NULL;
Node *third = NULL;
head = new Node();
second = new Node();
third = new Node();
head->data = 1;
head->next = second;
second->data = 2;
second->next = third;
third->data = 3;
third->next = NULL;
cout << "Before Adding:\n";
print(head);
head = add_end(head, 4);
cout << "\nAfter Adding: \n";
print(head);
return 0;
}
【问题讨论】:
标签: c++ linked-list