C언어/문제풀다 하나씩
메모리 풀로 링크드리스트 만들기
mcdn
2020. 6. 23. 11:49
반응형

아래는 모범 틀
#include <iostream>
using namespace std;
struct Node
{
char ch;
Node* next;
};
Node buf[100];
int bufCnt;
Node* head;
Node* myAlloc(int ch, Node* next)
{
buf[bufCnt].ch = ch;
buf[bufCnt].next = next;
return &buf[bufCnt++];
}
void addNode(char ch, Node *next)
{
head = myAlloc(ch, head);
}
int main()
{
return 0;
}

이건 내가 푼 것
#include <iostream>
using namespace std;
struct node {
char abc;
node* next;
};
node* head;
node* last;
node buf[10000000];
int bufcnt;
void addnode(char c) {
if (head == NULL) {
head = &buf[bufcnt++];
head->abc = c;
last = head;
}
else {
last->next = &buf[bufcnt++];
last = last->next;
last->abc = c;
//cout << last;
}
}
int main() {
addnode('A');
addnode('B');
addnode('C');
addnode('D');
addnode('E');
for (node* p = head;p != NULL;p = p->next) {
cout << p->abc << ' ';
}
return 0;
}
1. 메모리 풀

struct node 를 만들고
node에 대해 메모리를 넉넉하게 할당한다.
2. addnode

addnode 링크드리스트 연결하기
순서 중요하다.
head = NULL인 상태에서 &buf[bufcnt]로 주소 할당하고
bufcnt++로 bufcnt에 하나 더한다.
head에는 이제 node에 맞는 값을 집어넣을 수 있으니까 head->abc에 c를 넣는다.
마지막으로 last에다가 매번 더할거니까 last에도 head값을 복사한다.

그다음 이제 head에 NULL이 아닐 때
last에다가 값을 추가할 것임.
last에는 현재 값이 있는 상태이니
NULL값인 last-> next에다가 buf[bufcnt]를 할당한다.
bufcnt++로 bufcnt+=1을 하고
last = last->next로 가리키는 곳을 바꾼다.
last는 이제 방금 할당받은 buf[bufcnt]가 있으므로
last->abc로 값을 넣는다.
끝
반응형