【发布时间】:2021-03-09 09:05:57
【问题描述】:
我正在尝试实现我的单链表,但我遇到了这个问题:
当我尝试 pushBack 链接列表中的某些元素时,它只会打印我添加的 第一个。例如,如果我尝试 pushBack 2,3,4 - 它只会打印 2 个。
如果我想将链表中的某些元素向上推,它只会打印我添加的第三个。例如,如果我尝试 pushUp 2,3,4 - 它只会打印 4。
这是我的代码:
在此处输入代码
#include<iostream>
#include<vector>
using namespace std;
struct Node {
int data;
Node* next;
};
class LinkedList {
private:
// Create pointers for head and tail
Node *head , *tail;
public:
LinkedList(){
// Initiate them as null pointers
head = NULL;
tail = NULL;
}
public:
void pushBack(int value){
// Should add a node at the end of the linked list
Node* temp = new Node(); // temporary node which should be added
temp->data = value; // value to store
temp->next = NULL; // pointer to the next node
if(head != NULL){
// If there are some elements , then
temp->next = tail->next;
tail = temp;
}
if(head == NULL){
// If there are no elements , our node will be a head and a tail in the same time.
head = temp;
tail = temp;
}
}
void pushUp(int value){
// Shound add a node at the beginning of the linked list
Node* temp = new Node();
temp->data = value;
temp->next = NULL;
if(head == NULL){
// If there are no elements , our node will be a head and a tail in the same time.
head = temp;
tail = temp;
}
if(head != NULL){
// If there are some elements , just make our node to be new head.
temp->next = head->next;
head = temp;
}
}
void traversal(){
Node *temp = new Node();
temp = head;
while(temp != NULL){
cout << temp->data << " ";
temp = temp->next;
}
}
};
int main(){
// Pointer for our first node.
LinkedList a;
a.pushUp(2);
a.pushUp(124);
a.pushUp(3);
// a.pushBack(2);
// a.pushBack(124);
// a.pushBack(3); // Outputs only 2
a.traversal(); // Outputs only 3
}
【问题讨论】:
-
您在 pushUp 中的
(head != NULL)测试将始终通过,因为您刚刚在之前的测试中分配了一些东西给 head。 pushBack 中的temp->next = tail->next;对我来说也是错误的。 -
head != NULL必须是else。而在遍历中,你为什么要new Node? -
拿出铅笔和纸,画出发生了什么。 (有几个问题。)然后用铅笔和纸找出应该发生什么。然后将该过程翻译成代码。
-
我建议您逐行检查代码with the debugger。您将很快观察之前评论中所说的内容,看看出了什么问题。
标签: c++ data-structures singly-linked-list