C_C++

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

고니자니 2023. 4. 11. 15:45
반응형

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

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

typedef struct Node {
	int data;
	struct Node* next;
} Node;
// Node* head = NULL;

void append(struct Node** head, int data) {
	struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
	newNode->data = data;
	newNode->next = NULL;

	if (*head == NULL) {
		*head = newNode;
		return;
	}

	struct Node* last = *head;
	while (last->next != NULL) {
		last = last->next;
	}
	last->next = newNode;
}

int main()
{
	struct Node* head = NULL;
	append(&head, 1);
	append(&head, 2);
	append(&head, 3);

	printf("연결 리스트: ");
	struct Node* ptr = head;
	while (ptr != NULL) {
		printf("%d->", ptr->data);
		ptr = ptr->next;
	}
	printf("\n");

	return 0;
}

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

728x90
반응형