당신이 보여주는이 프로그램은 진짜 '팝'은 '변화'설명하는 '변화'가 될 것으로 보인다.
이동 : 당신은 다음 항목 (안 현재 머리)에 대한 포인터를 반환 할, 그리고
int myvalue;
intnode_t *newhead = shift(head, &myvalue);
로, 예를 들어
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;
}
호출 할 현재의 헤드 값으로 popped_value
설정
이 작업의 이름은 이며 목록에서 첫 번째 항목 값을 가져 와서 해당 요소를 제거합니다. pop은 일반적으로 으로 설정하고 마지막 항목 값을 취한 다음 해당 마지막 요소를 제거합니다.
이 알고리즘은 마지막 요소가 NULL
로 설정된 next
포인터를 가지고 가정 뭔가
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;
}
처럼
팝이 될 것이라고. 반환 값은 목록에 요소가 하나만 있으면 호출자에게 목록에 더 이상 요소가 없음을 알리기 위해
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
}
당신이 학생이기 때문에, 여기에 같은 일이
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;
}
을 수행 팝의 재귀 버전입니다 연구.
찾고있는 단어는 "팝"입니다. –
문제를 설명하지는 않지만'head = head-> next로 무엇을 기대하고 있습니까? popped_value = & head-> value'? 그리고'head '를 반환하기 전에 왜'자유 (head); –
다음 노드 값을 헤드 노드에 저장하고이 값을 popped_value가 가리키는 위치에 저장하려고했습니다. – student17