#include <iostream>
using namespace std;
typedef struct Node {
int data;
struct Node* next;
} Node;
Node* createNode(int data) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = data;
newNode->next = NULL;
return newNode;
}
void appendNode(Node** head, int data) {
Node* newNode = createNode(data);
if (*head == NULL) {
*head = newNode;
} else {
Node* current = *head;
while (current->next != NULL) {
current = current->next;
}
current->next = newNode;
}
}
void printList(Node* head) {
Node* current = head;
while (current != NULL) {
cout << current->data << " -> ";
current = current->next;
}
cout << "NULL" << endl;
}
void freeList(Node* head) {
Node* tmp;
while (head != NULL) {
tmp = head;
head = head->next;
free(tmp);
}
}
int main() {
Node* head = NULL;
appendNode(&head, 10);
appendNode(&head, 20);
appendNode(&head, 30);
cout << "Linked List: " << endl;
printList(head);
freeList(head);
return 0;
}
코드 실행 결과