링크드리스트 정렬 다시 해봤는데 안돼요 ㅠ
겨라
#includestdio.h
#includestdlib.h
struct node{
int value;
struct node* next;
};
struct node *head; //머리 노드
void init()
{
head = NULL;
}
//머리 노드 초기화
void show_list();
void insert_num();
void search_list();
void delete_list();
void array_list();
void main()
{
int sel;
while(1)
{
printf(1.Insert\n);
printf(2.Show\n);
printf(3.Delete\n);
printf(4.Search\n);
printf(5.Array number\n);
printf(6.End\n);
printf(Enter the wanted key : );
scanf(%d,&sel);
switch(sel)
{
case 1:
insert_num();
break;
case 2:
show_list();
break;
case 3:
delete_list();
break;
case 4:
search_list();
break;
case 5:
array_list();
break;
case 6:
exit(1);
}
}
}
void insert_num() //값을 삽입하는 함수이다.
{
struct node* temp;
struct node* tail;
//temp는 입력한 값을 받는 함수이고, tail은 리스트가 2개 이상일 경우 리스트의 끝을 찾기 위한 변수.
int num;
temp = (struct node*)malloc(sizeof(struct node));//나중에 free해줘야함.
printf(Enter the insert number :);
scanf(%d,&num);
temp-value = num;
temp-next = NULL;//이 구문이 꼭 필요하다.없을 경우 계속 에러 발생.중요.
if(head == NULL) //리스트가 없을 경우.
{
head = temp;
}
else if(head-next == NULL)//리스트가 1개 일 경우.
{
head-next = temp;
}
else//리스트가 2개 이상 일 경우.
{
tail = head;
while(tail-next != NULL)
{
tail = tail-next;
}
tail-next = temp;
//끝에 도달했을 경우 tail의 끝에다가 입력한 값을 링크시킨다.
//여기서 head는 temp를 받기 때문에 동적할당이 같이 된 상태라고 보면 된다.
//while문에서 tail-next != NULL 과 tail != NULL 의 차이점은 중요하다
/*
tail-next != NULL : 가장 마지막 노드를 가르키고 있을 경우
tail != NULL : 가리키는곳이 없을때, 즉 리스트의 마지막을 벗어났을 경우.
*/
}
}
void search_list()
//원하는 숫자가 있는지 검색하는 함수.
{
int num,flag;
struct node* check;
flag = 0 ;
check = head;
printf(Enter the search num : );
scanf(%d,&num);
while(check != NULL)
{
if(check-value == num)
{
puts(The key is exist);
flag =1;
break;
}
check = check-next;
}
if(flag ==0)
puts(The key is not exist);
}
void delete_list()
{
//지울때도 3가지를 고려해야 한다.
//1.리스트가 비어 있을경우
//2.list의 첫번째가 같을 경우
//3.list의 두번째가 같을 경우
int num;
struct node* curr;
struct node* prev;
printf(Enter the delete num : );
scanf(%d,&num);
if(head == NULL)//1번 case일 경우
{
}
else if(head-value == num)//2번 case일 경우
{
curr = head;
head = head-next;
free(curr);
}
else //3번 case일 경우.
{
prev=head;
curr=prev-next;
while(curr!=NULL && curr-value != num)
{
prev = curr;
curr = curr-next;
}
if(curr != NULL)
{
prev-next = curr-next;
free(curr);
}
}
}
void show_list() //삽입된 값들을 보여주는 함수.
{
struct node* tmp;
tmp = head;
printf(List : );
while(tmp != NULL)
{
printf(%d - , tmp-value);
tmp = tmp-next;
}
printf(\n);
}
void array_list()
{
struct node* check1;
struct node* check2;
struct node* tmp;
check1 =head;
check2=head-next;
while(check1!=NULL)
{
for( ; check2!=NULL;)
{
if(check1-value check2-value)
{
check1-next = check2-next;
check2-next = check1;
}
check2 = check2-next;
}
check1 = check1-next;
}
빨간 줄 부분에서 문제가 잇는거 같애요.
5 3 7 입력하면 3 5 7 나와야하는데 5 7만 나오고 3이 없어졌어요 . 어떻게 고쳐야 할지좀 알려주세요 ㅠㅠ}