연결리스트는 포인터로 연결된 논리적 선형리스트를 의미한다.
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node* nextNode;
} Node;
Node* Head = NULL;
void printList();
int add(int data);
int addFirst(int data);
bool addIndex(int data, int index);
bool delAll();
bool del(int index);
int main() {
add(10);
add(20);
add(30);
add(40);
add(50);
del(3);
printList();
return 0;
}
// 모든 리스트 출력
void printList() {
Node* ptr = Head;
if (Head == NULL) {
printf("비어있음\n");
return;
}
while (ptr != NULL) {
printf("%d \n", ptr->data);
ptr = ptr->nextNode;
}
}
// 공백일 경우 데이터 추가
int addFirst(int data) {
Head = (Node*)malloc(sizeof(Node));
Head->data = data;
Head->nextNode = NULL;
return data;
}
// 가장 마지막에 데이터 추가 (추가한 데이터 반환)
int add(int data) {
Node* ptr = Head;
if (Head == NULL) {
return addFirst(data);
}
while (ptr->nextNode != NULL) {
ptr = ptr->nextNode;
}
ptr->nextNode = (Node*)malloc(sizeof(Node));
ptr->nextNode->data = data;
ptr->nextNode->nextNode = NULL;
}
// index에 데이터 추가
bool addIndex(int data, int index) {
Node* ptr = Head;
if (Head == NULL) {
addFirst(data);
return 1;
}
for (int i = 0; i < index - 1 && ptr->nextNode != NULL; i++) {
ptr = ptr->nextNode;
}
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = data;
newNode->nextNode = ptr->nextNode;
ptr->nextNode = newNode;
return 1;
}
// 모든 원소 삭제
bool delAll() {
Node* del = NULL;
if (Head != NULL) {
while (Head != NULL) {
del = Head;
Head = Head->nextNode;
free(del);
}
return 1;
}
else return 0;
}
// 선택 원소 삭제
bool del(int index) {
Node* pPtr = Head;
Node* ptr = Head;
Node* del = NULL;
int i;
if (Head == NULL) {
printf("삭제할 데이터가 없음\n");
return 0;
}
else if (index == 0) {
Head = ptr->nextNode;
printf("삭제된 데이터 : %d\n", ptr->data);
free(ptr);
return 1;
}
for (i = 0; i < index; i++) {
if (ptr == NULL) {
printf("범위를 벗어남\n");
return 0;
}
pPtr = ptr;
ptr = ptr->nextNode;
}
pPtr->nextNode = ptr->nextNode;
printf("삭제된 데이터 : %d\n", ptr->data);
free(ptr);
return 1;
}
'알고리즘' 카테고리의 다른 글
원형 큐 (0) | 2023.05.03 |
---|---|
stack (0) | 2023.04.28 |
quick sort (0) | 2023.04.20 |
삽입 정렬 알고리즘 (0) | 2023.04.12 |
선택 정렬 알고리즘 (0) | 2023.04.11 |