1

我想知道setcdr,setcar和之间cdr的区别car。我知道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;
}
4

1 回答 1

6

术语carcdr来自 LISP(参见Wikipedia 条目)。它们在这种情况下的使用可能是指一种构造链表的特定方式:

  1. 每个节点有两个部分,carcdr
  2. car片段指向节点的内容,片段cdr指向列表中的下一个节点。
  3. 列表中最后一个节点的cdr片段设置为NULL或其等效项。

使用这种方法,该函数setcdr修改现有节点的cdr一部分(即,将节点的指针设置为列表中的下一个节点),因此没有任何内容可返回。

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

于 2013-11-11T00:47:47.223 回答