//삽입 검색 삭제 전체 출력
//링크드리스트: 노드안에 데이터와 연결된 주소를 같이 넣어 능동적인 데이터 변형을 할수 있도록 함
#include <stdio.h>
#include <malloc.h>
typedef struct node//리스트의 노드
{
int data;// 노드의 데이터
struct node *next;//다음 노드의 주소
}node;
typedef struct{
node *head;
}linkedlist;
linkedlist* createlist(void)
{
linkedlist *L;
L = (linkedlist*)malloc(sizeof(linkedlist));
L->head = NULL;
return L;
}
linkedlist* createlist(void);
void freelinkedlist(linkedlist*);
void input(linkedlist*, int);
void deletenode(linkedlist*);
void printlist(linkedlist*);
void menu();
void input(linkedlist *L)
{
int k;
printf("----------------------------\n");
node *newnode;
node *p;
newnode = (node*)malloc(sizeof(node));
printf("Please type in a number you wish to insert\n");
scanf("%d", &k);
newnode->data = k;
newnode->next = NULL;
if(L->head == NULL)
{
L->head = newnode;
printf("insert complete \n");
printf("----------------------------\n");
return;
}
p = L->head;
while(p->next!=NULL)
p = p->next;
p->next = newnode;
printf("insert complete \n");
printf("----------------------------\n");
}
void deletenode(linkedlist *L)
{
node* previous;
node* current;
printf("----------------------------\n");
if(L->head ==NULL)
{
printf("delete successful/n");
printf("----------------------------\n");
return;
}
if(L->head->next==NULL)
{
free(L->head);
L->head = NULL;
printf("delete successful\n");
printf("----------------------------\n");
return;
}
else
{
previous = L->head;
current = L->head->next;
while(current->next!=NULL)
{
previous = current;
current = current->next;
}
free(current);
previous->next = NULL;
}
printf("delete successful\n");
printf("----------------------------\n");
}
void freelinkedlist(linkedlist* L)
{
node *p;
printf("----------------------------\n");
while(L->head!= NULL)
{
p = L->head;
L->head = L->head->next;
free(p);
p=NULL;
}
printf("all emptied\n");
printf("----------------------------\n");
}
void printlist(linkedlist *L)
{
node *p;
printf("----------------------------\n");
printf("L = (");
p = L->head;
while(p !=NULL)
{
printf("%d", p->data);
p = p->next;
if(p!=NULL)
printf(", ");
}
printf(")\n");
printf("----------------------------\n");
}
void menu()
{
int m=0;
linkedlist *L;
L = createlist();
printf("Welcome to list management!\n");
while(m!=5)
{
printf("Press 1 for insert, 2 for delete, 3 for print all, 4 to free all, 5 to quit\n");
scanf("%d", &m);
if(m==1)
input(L);
else if(m==2)
deletenode(L);
else if(m==3)
printlist(L);
else if(m==4)
freelinkedlist(L);
else
printf("Please enter a number that is between 1 and 5\n");
}
}
int main()
{
menu();
return 0;
}