본문 바로가기

셈틀/C/C++

해결

사용자 삽입 이미지


거의 1달 남짓 나를 괴롭혀 오던 문제를 해결했다. 문제는 pointer를 인수로 넘겼을 때, 그 주소에 들어있는 데이터는 따로 리턴을 해주지 않아도 바뀐 값이 함수 밖으로 나간 뒤에도 유지가 되지만, 주소를 바꾼 경우는 꼭 리턴을 해주어야 한다는 것이었다. 링크드리스트에서 head의 주소가 바뀐 경우가 여기에 해당...

 //function to delete the node user wants to delete
//head is an index which points the first node of linked list
record* del_elmt(record *head){
	int num; //integer to get the ID of node to delete
	int pre_amount=amount; //set the number of exist nodes
	record *prev;	 
	record *curnt;
	record *del=head;//temporary in case the node to delete is the head.

	prnt_list(head); //display all items in the list.

	if(head==NULL){	//if list is empty
		puts("지울 이름이 없습니다.\n");
	}
	else{	//if list is not empty
		message("지울 번호를 입력하세요. : ");
		scanf("%d", &num);
		if(del->crt_odr==num){ //if the first node is the node to delete
			if(amount==1){//if the head is the only one node in the list
				head=NULL;
			}else{//if there are another nodes except head
				head=head->next;
			}
			printf("%d(%s)를 삭제하였습니다.\n", del->crt_odr, del->name);
			amount--; //decrease the number of nodes
			free(del); //free the old head node
		}
		else{//if the node to delete is in the middle of the list
			prev=head;
			curnt=head->next;
			while(curnt!=0){ //explore by the end of list
				if(curnt->crt_odr==num){//if curnt is the node to delete
					printf("%d(%s)를 삭제하였습니다\n.", curnt->crt_odr, curnt->name);
					amount--; //decrease the number of nodes
					//make previous node point to next node of the deleted
					prev->next=curnt->next;
					free(curnt);//free the memory of the deleted node
					break;
				}
				else{
					prev=prev->next;
					curnt=curnt->next;
				}
			}//end of while 
		}//end of else
	}
	if (pre_amount==amount){
		puts("자료를 찾는데 실패했습니다.\n");
	}
	return head;// return new head pointer
}


이걸 또 어디에 써먹을까만은, 단순한 문제일 수 있지만, 옛날에 나로서는 ..ㅎㅎ
무언가 레벨 업 한 느낌.

사용자 삽입 이미지