단순 연결 리스트인데 출력결과가 이상하게 나와요.
노을빛
질문 제목 : 질문 내용 :
#include stdio.h
#include stdlib.h
#include string.h
#define true 1
#define false 0
typedef struct listnodetype
{
int data;
struct listnodetype* plink;
} listnode;
typedef struct linkedlisttype
{
int currentelementcount;// 현재 저장된 원소의 개수
listnode headernode;// 헤더 노드(header node)
} linkedlist;
linkedlist* creaditlist(linkedlist* plink);
int addelement(linkedlist* plink,int position,int data);
void display(linkedlist* plink);
listnode* getelement(linkedlist* plink,int position);
int getlenth(linkedlist* plink);
int main()
{
linkedlist* plink=null;
plink=creaditlist(plink);
//listnode data;
//원소추가
if(plink != null){
addelement(plink,0,1);
addelement(plink,1,3);
addelement(plink,2,5);
display(plink);
}
return 0;
}
linkedlist* creaditlist(linkedlist* plink)
{
plink=(linkedlist*)malloc(sizeof(linkedlist));
if(plink == null){
puts(헤더노드 메모리 할당 오류!);
return null;
}
memset(plink,0,sizeof(linkedlist));
return plink;
}
int addelement(linkedlist* plink,int position,int data)
{
int ret=false;
int i;
listnode* pnewnode=null;
listnode* pprenode=null;
if(plink != null)
{
if(position = 0 &&
position = plink-currentelementcount){
//새로운원소메모리할당
pnewnode=(listnode*)malloc(sizeof(listnode));
if(pnewnode != null){
pnewnode-data = data;
pnewnode-plink=null;
}
else{
puts(새로운 메모리 할당 오류!);
return ret;
}
//노드탐색
pprenode=&(plink-headernode);
for(i=0; iposition ; i++){
pprenode=pprenode-plink;
}
//노드관계재정립
pnewnode-plink=pprenode-plink;
pprenode-plink=pnewnode;
plink-currentelementcount++;
ret=true;
}
else{
printf(인덱스 오류!\n);
printf(현재 인덱스: [%d], 입력 인덱스: [%d]\n,
plink-currentelementcount,position);
}
}
else{
puts(메모리 할당 오류!);
}
return ret;
}
void display(linkedlist* plink)
{
int i,arrlen;
printf(현재 원소 개수: %d\n,plink-currentelementcount);
arrlen=getlenth(plink);
for(i=0; iarrlen; i++){
printf([%d]: %d\n, i,getelement(plink,i)-data);
}
}
listnode* getelement(linkedlist* plink,int position)
{
int i;
listnode* node=null;
listnode* preturn=null;
if(plink != null){
if(position =0 &&
position plink-currentelementcount){
node=&(plink-headernode);
for(i=0; iposition; i++){
node=node-plink;
}
preturn=node;
}
}
return preturn;
}
int getlenth(linkedlist* plink)
{
int len=0;
if(plink != null){
len=plink-currentelementcount;
}
return len;
}
[0]: 1
[1]: 3
[2]: 5
나와야하는데 0,1,3
으로 나오는데..
왜 그런거죠.?