1) ์ผ๋ฐ์ ์ผ๋ก ๋ฐฐ์ด์ ์ฌ์ฉํ์ฌ ๋ฐ์ดํฐ๋ฅผ ์์ฐจ์ ์ผ๋ก ์ ์ฅํ๊ณ , ๋์ดํ ์ ์์ง๋ง
2) ๋ฐฐ์ด์ ์ฌ์ฉํ๋ ๊ฒฝ์ฐ, ๋ฉ๋ชจ๋ฆฌ ๊ณต๊ฐ์ด ๋ถํ์ํ๊ฒ ๋ญ๋น๋ ์ ์๋๋ฏ๋ก
3) ์ด๋ ์ฐ๊ฒฐ ๋ฆฌ์คํธ๋ก ๋์ฒดํ ์ ์๋ค
1) ๋ฐ์ดํฐ๋ฅผ ์์ฐจ์ ์ผ๋ก ์ ์ฅ, ์ฒ๋ฆฌํ ๋๋ ๋ฐฐ์ด ๊ธฐ๋ฐ์ ๋ฆฌ์คํธ๋ฅผ ์ด์ฉ
#include <stdio.h>
#define INF 10000
int arr[INF];
int count = 0;
void addBack(int data) {
arr[count] = data;
count++;
}
void addFirst(int data) {
for (int i = count; i >= 1; i--) {
arr[i] = arr[i - 1];
}
arr[0] = data;
count++;
}
void show() {
for (int i = 0; i < count; i++) {
printf("%d ", arr[i]);
}
}
int main(void) {
addFirst(4);
addFirst(5);
addFirst(1);
addBack(7);
addBack(6);
addBack(8);
show();
system("pause");
return 0;
}
๊ทธ๋ ๋ค๋ฉด?! ํน์ ํ ์์น์ ์์๋ฅผ ์ญ์ ํ๋ ํจ์๋ ์ด๋ป๊ฒ ๋ง๋ค ์ ์์๊น?
// ํน์ ํ index๋ฅผ ๋ฐ์์ ํด๋น index ์์น์ ๋ท ์์๋ฅผ ์์ผ๋ก ๋น๊ธฐ๋ ๋ฐฉ์์ผ๋ก ๊ตฌํ
void removeAt(int index) {
for (int i = index; i < count - 1; i++) {
arr[i] = arr[i + 1];
}
count--;
}
index
๋ฅผ ํ์ฉ#define INF 10000
๐ ์ฐธ๊ณ !
- ํฌ์ธํฐ๋? โฌ ๏ธํด๋ฆญ
- ๊ตฌ์กฐ์ฒด๋?
data
์ ๋ค์ ๋
ธ๋๋ฅผ ๊ฐ๋ฆฌํค๋ next
๋ก ๊ตฌ์ฑ๋์ด ์๋คํค๋(Head)
๋ผ๊ณ ํ๋ฉฐ ๋ณ๋๋ก ๊ด๋ฆฌํ๋ค**NULL
**์ ์ถ๊ฐํ๋ค1) ์ฐ๊ฒฐ ๋ฆฌ์คํธ ๊ตฌ์กฐ์ฒด ๋ง๋ค๊ธฐ
#include <stdio.h>
#include <stdlib.h>
typedef struct {
int data;
struct Node *next; // ๋ค์ ๋
ธ๋๋ฅผ ๊ฐ๋ฆฌํค๋ ๋ณ์. ํฌ์ธํฐ ๋ณ์
} Node;
Node *head; // ํฌ์ธํฐ ๋ณ์๋ฅผ ํ์ฉํด ๋์ ํ ๋น์ด ์ด๋ฃจ์ด์ง๋๋ก ํ๋ค
2) ์ฐ๊ฒฐ ๋ฆฌ์คํธ ๊ตฌ์กฐ์ฒด ์ฌ์ฉํด๋ณด๊ธฐ
malloc()
ํจ์๋ก ๋์ ํ ๋นํ๊ธฐint main(void) {
head = (Node*) malloc(sizeof(Node));
Node *node1 = (Node*) malloc(sizeof(Node));
node1->data = 1;
Node *node2 = (Node*) malloc(sizeof(Node));
node2->data = 2;
head->next = node1;
node1->next = node2;
node2->next = NULL;
Node *cur = head->next;
while (cur != NULL) {
printf("%d ", cur->data);
cur = cur->next;
}
system("pause");
return 0;
}
3) ๋ ธ๋ ์ฝ์
void addFront(Node *root, int data) {
Node *node = (Node*) malloc(sizeof(Node));
node->data = data;
node->next = root->next;
root->next = node;
}
4) ๋ ธ๋ ์ญ์
void removeFront(Node *root) {
Node *front = root->next;
root->next = front->next;
free(front);
}
5) ํ ๋น๋ ๋ฉ๋ชจ๋ฆฌ ํด์
free()
ํจ์๋ก ๋
ธ๋๋ฅผ ํ๋์ฉ ์ ๊ทผํด์ ํด์ ํด์ผ ํจvoid freeAll(Node *root) {
Node *cur = head->next;
while (cur != NULL) {
Node *next = cur->next;
free(cur);
cur = next;
}
}
6) ์ฐ๊ฒฐ ๋ฆฌ์คํธ ์ ์ฒด ์ถ๋ ฅ ํจ์
void showAll(Node *root) {
Node *cur = head->next;
while (cur != NULL) {
printf("%d ", cur->data);
cur = cur->next;
}
}
7) ์์ฑ๋ ์ฐ๊ฒฐ ๋ฆฌ์คํธ ์ฌ์ฉํ๊ธฐ
int main(void) {
head = (Node*) malloc(sizeof(Node));
head->next = NULL;
addFront(head, 2);
addFront(head, 1);
addFront(head, 7);
addFront(head, 9);
addFront(head, 8);
removeFront(head);
showAll(head);
freeAll(head);
system("pause");
return 0;
}