Data structure
단방향 연결리스트(c언어)
study ticket
2022. 3. 5. 21:39
기본main함수 설정
- 동적할당을 이용하기때문에 메모리해제가 필요
int main()
{
node* head = (node*)malloc(sizeof(node));
head->next = NULL;
node* curr = head->next;
while (curr != NULL)
{
printf("%d\n", curr->data);
curr = curr->next;
}
curr = head->next;
while (curr != NULL)
{
node* next = curr->next;
free(curr);
curr = next;
}
}
노드를 위한 구조체
typedef struct NODE
//단일방향의 노드 구조체
{
int data;
struct NODE* next;
}node;
헤드다음의 노드를 추가하는 함수
void addNode(node* target, int data)
//헤드다음에 노드를 추가하는 함수
{
node* newNode = (node*)malloc(sizeof(node));
newNode->next = target->next;
newNode->data = data;
target->next = newNode;
}
헤드다음의 노드를 삭제하는 함수
void removeNode(node* target)
//헤더다음 노드를 삭제하는 함수
{
node* remove = target->next;
target->next = remove->next;
free(remove);
}
특정위치에 노드를 삽입하는 함수
void insert(node* target, int pos, int data)
//특정위치에 노드를 삽입하는 함수
{
node* curr = target;
node* newNode = (node*)malloc(sizeof(node));
newNode->data = data;
newNode->next = NULL;
if (pos == 0)
{
newNode->next = target->next;
target->next = newNode;
}
else
{
int cnt = 0;
while (cnt != pos)
{
if (cnt == (pos - 1))
{
newNode->next = curr->next;
curr->next = newNode;
}
curr = curr->next;
cnt++;
}
}
}
728x90