链接列表在类私有C ++中

时间:2015-11-02 23:23:39

标签: c++ pointers linked-list

我接近c ++而且我在一个班级里面工作。我试图将一个字符数组传递给链表。不知何故,当我打印尝试打印出来。它反过来了。我试着为什么我的代码这样做,但我似乎无法弄明白。

class foo{

public:
 foo(const char * s =""){
    head = Node::toList(s);
 }
 void print(ostream & in){
 for(ListNode *p = head; p!= nullptr;p=p->next)
    out << p->info;
 }

private:
struct Node{
 char info;
 Node *next;
 Node(char newInfo, Node *newNext):info(newNext),next(newNewxt){
 }
 static Node *toList(const char *s){
 Node *temp = nullptr;
 int x=0;
 for(;s[x] != '\0';x++){
     temp = new Node(s[x],temp); // Part where I do understand why I am getting reverse
 }
 return temp;
 }
Node *head;
}; 
ostream & operator << (ostream & out, foo src){
src.print(out);
return out;
};

任何提示或建议都会很棒。

1 个答案:

答案 0 :(得分:0)

如果您希望列表使用其直接字符顺序由字符串初始化,则该函数可以按以下方式查找

static Node * toList( const char *s )
{
    Node *head = nullptr;

    for ( Node **temp = &head; *s; ++s )
    {
        *temp = new Node( *s, nullptr );
        temp = &( *temp )->next;
    }

    return head;
}        

考虑到问题中显示的代码片段不会编译。

除了语法错误之外,您不能将operator <<声明为类成员函数,以便在流中输出类的对象。

相关问题