【发布时间】:2016-11-09 03:09:09
【问题描述】:
当指针处于“私有”状态时,我无法理解如何使用指针。
主要是我不知道如何获取和设置指针的值
我想创建一个没有字符值的头尾节点。 然后创建位于头部和尾部之间的新节点,并将新节点添加到列表的末尾(尾部之前)。
代码运行,但是当我使用打印功能时它什么也没做。
对不起,如果我的格式错误并且代码太长。
这是我班级的代码:
#include <iostream>
using namespace std;
class node
{
public:
node(void)// constructor for empty nodes
{
left_link = NULL;
right_link = NULL;
}
node(char x) // constructor for nodes with given value
: anything(x)
{ }
char get_char() // return character
{
return anything;
}
void setLeftLink(node *left)
{
left_link = left;
}
void setRightLink(node *right)
{
right_link = right;
}
node *getlefttLink()
{
return left_link;
}
node *getRightLink()
{
return right_link;
}
private:
node *left_link;
char anything;
node *right_link;
};
这是我的功能:
void append(node *&head, node *&tail);
void print(node *head);
void append(node *&head, node *&tail)
{
char c;
cout << "Please enter a single character: ";
cin >> c;
node *current = new node(c);
cout << current->get_char() << endl;
if(head == NULL && tail == NULL)
{
head->setRightLink(current);
tail->setLeftLink(current);
current->setLeftLink(head);
current->setRightLink(tail);
}
else
{
tail->setRightLink(current);
current->setLeftLink(tail);
tail = current;
tail->setRightLink(NULL);
}
}
// print function
void print(node *head)
{
node* temp;
temp = head;
while(temp->getRightLink()!=NULL){
cout<<temp->get_char()<<endl;
temp = temp->getRightLink();
}
}
这是我的主要内容:
int main()
{
char choice;
node *head = new node;
node *tail = new node;
cout << "Please choose one menu option at a time:\n"
<< "1 = Append\n"
<< "2 = Print list\n"
<< "3 = Exit\n\n";
do
{
cout << "Menu option(1-3): ";
cin >> choice;
switch (choice)
{
case '1': append(head, tail); // add to the end of list.
break;
case '2': print(head); // print list
break;
case '3': cout << "end program\n\n";
break;
default: cout << "try again\n";
break;
}
}while(choice != '3');
return 0;
}
【问题讨论】:
-
我怀疑您的问题与私有变量有关。
-
代码运行,但是当我使用打印功能时它什么也没做。我给你的建议是学会使用你的调试器。单步执行查看变量的代码..
-
您要么误解了链表概念,要么误解了 C++ 指针。如果你没有元素,那么你必须创建一个新的节点,它将成为头和尾,然后将它的左右邻居设置为
nullptr。查看append函数中的if语句,它涉及未定义的行为。
标签: c++ class pointers linked-list private