C_C++

(C언어) 연결리스트: 맨 앞에 노드 추가하기 Linked List

고니자니 2023. 4. 12. 19:02
반응형

연결리스트에서 맨앞에 노드를 추가하는 C언어 코드입니다.

맨 뒤에 노드를 추가하는 코드도 있습니다. 이 블로그에서 [연결리스트]로 검색해 보세요.

 

#include <stdio.h>
#include <stdlib.h> 

typedef struct Node {
	int data;
	struct Node* next;
} Node;

void insert(struct Node** headRef, int data) {
	struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
	newNode->data = data;
	newNode->next = *headRef;
	*headRef = newNode;
}

void print(struct Node* head)
{
	struct Node* ptr = head;
	while (ptr != NULL) {
		printf("%d -> ", ptr->data);
		ptr = ptr->next;
	}
	printf("\n");
}

int main()
{
	struct Node* head = NULL;

	insert(&head, 5);
	insert(&head, 4);
	insert(&head, 3);
	print(head);

	insert(&head, 2);
	insert(&head, 1);
	print(head);

	return 0;
}

연결리스트: 맨앞에 노드 추가하기

 

728x90
반응형