Coding Test/C_C#_C++
[C] 단방향 연결리스트
lim.dev
2020. 12. 31. 06:56
간단한 연결리스트를 구현했습니다.
단방향이라 중간 노드를 삭제할 때 앞 노드의 정보를 따로 찾아줬습니다.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef struct Data{
int index;
char name[20];
char phone[20];
}Data;
typedef struct Node{
Data data;
struct Node* Next;
}Node;
Node* create(Data data, int cnt) {
Node* newnode = (Node*)malloc(sizeof(Node)*sizeof(Data));
newnode->data.index = cnt;
strcpy(newnode->data.name, data.name);
strcpy(newnode->data.phone, data.phone);
newnode->Next = NULL;
}
void Index(Node* head) {
int cnt = 1;
Node* curr = head;
while (curr != NULL) {
curr->data.index = cnt;
curr = curr->Next;
cnt++;
}
}
void Insert(Node** head, Node* newnode){
if (*head == NULL) {
*head = newnode;
}
else{
Node* prev = (*head);
while (prev->Next != NULL){
prev = prev->Next;
}
prev->Next = newnode;
}
}
void Remove(Node** head, Node* prev, Node* rm) {
if (*head == rm) {
*head = rm->Next;
}
else if ((rm->Next != NULL) && (prev != NULL)) {
prev->Next = rm->Next;
}
else if (rm->Next == NULL) {
prev->Next = NULL;
}
free(rm);
}
Node* Search(Node* head, int index){
Node* prev = head;
int cnt = 0;
while (prev != NULL) {
if (cnt++ == index) {
return prev;
}
prev = prev->Next;
}
return NULL;
}
void PrintAll(Node* head){
while (head!=NULL){
printf("%i %s %s \n", head->data.index, head->data.name, head->data.phone);
head = head->Next;
}
}
int main(){
int i = 0;
int cnt = 0;
int input = 0;
Node* head = NULL;
Node* newNode = NULL;
Node* curr = NULL;
Data data;
while (1) {
printf("======================================\n");
printf("1)추가\t2)삭제\t3)검색\t4)나열\t5)종료\t\n");
printf("input: ");
scanf("%d", &input);
if (input == 1) {
printf("name phoneNum: ");
scanf("%s %s", data.name, data.phone);
cnt++;
newNode = create(data, cnt);
Insert(&head, newNode);
continue;
}
else if (input == 2){
printf("indexNum: ");
scanf("%d", &i);
curr = Search(head, i - 2);
newNode = Search(head, i - 1);
Remove(&head, curr, newNode);
Index(head);
}
else if (input == 3) {
printf("indexNum: ");
scanf("%d", &i);
curr = Search(head, i-1);
printf("%d %s %s \n", curr->data.index, curr->data.name, curr->data.phone);
continue;
}
else if (input == 4) {
PrintAll(head);
continue;
}
else if (input == 5) {
break;
}
else {
printf("wroung input\n");
}
}
}