了解链接列表中的cdr和car差异

时间:2013-11-11 00:38:45

标签: c++ pointers

我想知道setcdrsetcarcdrcar之间的差异。我知道car指的是节点的值,而cdr函数指的是节点中的下一个指针,但我不明白这些差异。

setcdr功能:

void setcdr( Node* p, Node* q ) {

    assert (p != nullptr);
    p->next = q;
}

void,那么如何设置链表呢?它不应该返回Node吗?

//returns the data field of the Node

// if p is the nullptr, we cannot get its data ...exit abruptly

int car( Node* p ) {

    assert (p != nullptr);
    return( p->value );
}

// returns the next field of the Node

// if p is the nullptr, we cannot get its next.... exit abruptly

Node* cdr( Node* p ) {

    assert (p != nullptr);
    return( p->next );
}

void setcar( Node* p, int x ) {

    assert (p != nullptr);
    p->value = x;
}

1 个答案:

答案 0 :(得分:5)

条款carcdr来自LISP(请参阅Wikipedia entry)。它们在这种情况下的使用可能是指构建链表的一种特殊方式:

  1. 每个节点都有两个部分,carcdr
  2. car部分指向节点的内容,cdr部分指向列表中的下一个节点。
  3. 列表中最后一个节点的cdr部分设置为NULL或其等价物。
  4. 使用这种方法,函数setcdr修改 现有节点的cdr块(即设置节点指向下一个节点的指针)列表中的节点),所以没有什么可以返回的。

    应该有办法创建新的Node,但它不会使用您在帖子中提到的任何功能。

相关问题