C 如何实现与推送相反的功能?
我试图实现一个与push相反的函数:它检索 值存储在链接列表的头节点中,然后从链接列表中删除该节点 参数头指向链接列表中的第一个节点 我试图让函数将列表头节点中的值复制到参数popped_value指向的位置,然后将头节点与列表解除链接,并返回指向修改列表中第一个节点的指针 这是我目前掌握的代码。我真的被困在这上面了,非常感谢你的帮助。多谢各位C 如何实现与推送相反的功能?,c,list,singly-linked-list,C,List,Singly Linked List,我试图实现一个与push相反的函数:它检索 值存储在链接列表的头节点中,然后从链接列表中删除该节点 参数头指向链接列表中的第一个节点 我试图让函数将列表头节点中的值复制到参数popped_value指向的位置,然后将头节点与列表解除链接,并返回指向修改列表中第一个节点的指针 这是我目前掌握的代码。我真的被困在这上面了,非常感谢你的帮助。多谢各位 typedef struct intnode { int value; struct intnode *next; } intnode_t;
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;
}
你展示的节目似乎是一个“移位”,真正的“流行”在“移位”下面描述 Shift:您希望返回指向下一个项目(而不是当前标题)的指针,并将
popped_值
设置为当前标题值
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;
}
被称为,例如
int myvalue;
intnode_t *newhead = shift(head, &myvalue);
请注意,此操作通常命名为shift,因为您从列表中获取第一个项目值,并删除该元素pop通常是当您获取(设置popped_值
到它)最后一个项目值,然后删除最后一个元素时
那个流行音乐大概是
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
,如果列表只有一个元素来告诉调用者列表中没有更多的活动元素
你这样叫“爸爸”
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;
}
用于学习。你要搜索的单词是“Pop”。你没有描述问题,但是你对
head=head->next有什么期待;弹出的值=&head->value
?为什么免费(head)
在返回head
之前,我试图将下一个节点值存储到head节点中,然后将该值存储到弹出的_值所指向的位置。