c++ - 最后在C++的链表中添加节点

标签 c++ linked-list

我尝试实现单向链表。我的 addAtLast() 函数没有正确执行。执行此函数时程序崩溃。请提出一些更改建议。

class LList
{
public:
    int noOfNodes;
    Node const *start;/*Header Node*/

    LList()
    {
        start=new Node;
        noOfNodes=0;start=0;
    }

    void addAtFront(Node* n)
    {
        /*
        cout<<endl<<"class"<<n;
        cout<<"start"<<start;
        cout<<"data in node";n->print();
        */
        n->next=const_cast<Node*>(start);
        start=n;
        // cout<<" next=";start->print();
        noOfNodes++;
    }

    void addAtLast(Node* n)
    {
        Node *cur=const_cast<Node*>(start);
        if (start==NULL)
        { 
            start=n;
            return;
        }
        while(cur->next!=NULL)
        {
            cur=cur->next;
        }
        cur->next=n;
        noOfNodes++;
    }

    int getPosition(Node data)
    {
        int pos=0;
        Node *cur=const_cast<Node*>(start);
        while(cur!=NULL)
        {
            pos++;
            if(*cur==data)
            {
                return pos;
            }
            cur=cur->next;
        }
        return -1;//not found
    }

    Node getNode(int pos)
    {
        if(pos<1)
            return -1;// not a valid position
        else if(pos>noOfNodes)
            return -1; // not a valid position

        Node *cur=const_cast<Node*>(start);
        int curPos=0;
        while(cur!=NULL)
        {
            if(++curPos==pos)
                return *cur;
            cur=cur->next;
        }
    }

    void traverse()
    {
        Node *cur=const_cast<Node*>(start);
        while(cur!=NULL)
        {
            //   cout<<"start"<<start;        
            cur->print();
            cur=cur->next;
        }
    }  

    ~LList()
    {
        delete start;
    }
};

最佳答案

void addAtLast(Node* n) {
    Node *cur=const_cast<Node*>(start);
    if(start==NULL) {
        start=n;
        n->next = NULL;
        noOfNodes++;
        return;
    }
    while(cur->next!=NULL) {
        cur=cur->next;
    }
    cur->next=n;
    n->next = NULL;  // Added
    noOfNodes++;
}

关于c++ - 最后在C++的链表中添加节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13340302/

相关文章:

c++ - 如何在 NS-3 中使用多路径路由

c++ - bool 类型的按位运算和逻辑运算相同吗?

c++ - 添加两个矩阵打印一列垃圾数据c++

c++ - 类不是类模板

c - 从链表中搜索并删除节点

c - C 中的段错误编译器错误

c - 将字符串列表添加到 LinkedList

c++ - 无法访问类中的常量静态成员

c - 将链表作为参数传递时出错

c - 在链表中输入元素时进行迭代