【问题标题】:C++ LinkedList struct referenced as Double Pointer, and need to access Next NodeC++ 链表结构被引用为双指针,需要访问下一个节点
【发布时间】:2012-08-26 00:26:29
【问题描述】:

好的,所以我设置了一个链接列表结构:

struct ListNode {
    ListNode* next;
    int data;
    ListNode(int in) {
        data = in;
        next = NULL;
    }
    ListNode(int in, ListNode* n) {
        data = in;
        next = n;
    }
};

连同插入功能:

bool insertNode(ListNode **head, int position, int data) {
    if (position == 0) {
        ListNode *element = new ListNode(data, *head->next);
        *head->next = element;
        return true;
    }
    else if (head == NULL)
        return false;
    else {
        insertNode(head->next, position-1, data);
    }
}

如何访问 head 的下一个元素?使用当前的代码,我收到以下错误消息:

request for member ‘next’ in ‘* head’, which is of non-class type ‘ListNode*’

【问题讨论】:

    标签: c++ pointers linked-list double-pointer


    【解决方案1】:

    这应该可以解决问题

    (*head)->next
    

    编辑:有关操作员优先级的更多信息http://en.cppreference.com/w/cpp/language/operator_precedence

    【讨论】:

    • 成功!感谢您的及时回复!
    • 说得太早了。它适用于前两个 head->next 调用,但是当我将它传递给我的递归调用时,它不喜欢它:无法将参数 '1' 的 'ListNode*' 转换为 'ListNode**' 到 'bool insertNode(ListNode**, int, int)'
    • 如果你看一下操作符的优先级,你应该知道它为什么起作用了!
    • '&head->next' 不起作用。它给了我最初的错误消息
    • Uffff ;) 我累了。 &(*head)->下一个
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多