你展示的节目好像是'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;
}
供你学习。