【问题标题】:How to implement function that is the inverse of push?如何实现与推送相反的功能?
【发布时间】:2018-05-03 04:24:16
【问题描述】:

我正在尝试实现一个与 push 相反的函数:它检索 值存储在链表的头节点中,然后从链表中删除该节点。

参数head指向链表中的第一个节点。

我试图让函数将列表头节点中的值复制到参数 popped_value 指向的位置,然后从列表中取消头节点的链接并返回指向修改后列表中第一个节点的指针。

这是我到目前为止的代码。我真的坚持这一点,非常感谢任何帮助。谢谢。

typedef struct intnode {
  int value;
  struct intnode *next;
  } intnode_t;


intnode_t *pop(intnode_t *head, int *popped_value) {

assert(head!=NULL);

head = head->next;

popped_value=&head->value;


free(head);

return head;

}

【问题讨论】:

  • 您要搜索的词是“Pop”。
  • 您没有描述问题,但您对head = head->next; popped_value = &head->value 有什么期望?为什么在返回head之前先free(head);
  • 我试图将下一个节点值存储到头节点中,然后将该值存储到 popped_value 指向的位置。

标签: c list singly-linked-list


【解决方案1】:

你展示的节目好像是'shift',真正的'pop'在'shift'下面描述。

Shift:要返回指向下一项(不是当前头)的指针,并将popped_value设置为当前头值

intnode_t *shift(intnode_t *head, int *popped_value) {
   assert(head!=NULL);
   // get next pointer here, since 'head' cannot be used after it's been freed
   intnode_t *next = head->next;
   // sets the int variable which pointer is given as argument to
   // the current head value
   *popped_value = head->value; 
   // you can now free head without worries
   free(head);
   // and return the next element (becoming the new head)
   return next;
}

例如被称为as

int myvalue;
intnode_t *newhead = shift(head, &myvalue);

请注意,此操作通常命名为 shift,因为您从列表中获取第一个项目值,然后删除该元素。 pop 通常是当您获取(将popped_value 设置为)last 项目值,然后删除最后一个元素。

pop 会是这样的

intnode_t *pop(intnode_t *head, int *popped_value) {
   assert(head!=NULL);
   intnode_t *last,*previous;
   // get last and last's previous element
   for(previous=NULL,last=head ; last->next ; last=last->next) previous=last;
   // get the last value
   *popped_value = last->value; 
   // free last element
   free(last);
   // If at least two elements, tell the previous one there is no more 
   if (previous) previous->next = NULL; // previous is last now
   // return the head or NULL if there no more element
   // (previous is NULL if there was only one element, initially)
   return previous ? head : NULL;
}

此算法假定最后一个元素的next 指针设置为NULL。如果列表只有一个元素告诉调用者列表中没有其他元素,则返回值将再次为head(前往列表)或NULL

你这样叫'pop'

int myvalue;
// head had to be declared and initialized before
head = pop(head, &myvalue);
if ( ! head) { // no more element
   break; // for instance, depending on your program
}

因为你是学生,这里有一个递归版本的 pop 做同样的事情

intnode_t *recpop(intnode_t *this, int *popped_value) {
    if (this->next) {
        // this is not the last element
        intnode_t *next = recpop(this->next, popped_value);
        // next element was the last
        if ( ! next) this->next = NULL;
    }
    else {
        // this is the last element
        *popped_value = this->value;
        free(this);
        this = NULL;
    }
    return this;
}

供你学习。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-10
    • 2021-10-05
    相关资源
    最近更新 更多