1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
#include <stdio.h>
#include <stdlib.h>
typedef struct node {
    int data;
    struct node *next;
} Node;
 
typedef struct {
    Node *p;
} LList;
 
void initList(LList *list)
{
    list->p = (Node *)malloc(sizeof(Node));
    list->p->data=-1;
    list->p->next = NULL;
}
 
void cleanupList(LList *list)
{
    Node *tmp;
    while(tmp)                            //tmp가 NULL을 만날때( tmp의 값이있다면 참)
    {
        Node *del = tmp;
        tmp = tmp->next;
        free(del);
    }
    
    list->p = NULL;
}
 
void printList(const LList *list)
{    //==for(Node *tmp = list->p->next; tmp != NULL; tmp=tmp->next)
    for(Node *tmp = list->p->next; tmp; tmp = tmp->next) 
      printf("%d ", tmp->data);
    printf("\n");
}
 
void insertNode(LList *list, int data) //asending sorting..
{
    Node *tmp1 = list->p;
    Node *tmp2 = list->p->next;
    
    while(tmp2)//tmp2 or tmp2==data find
    {
        if(data < tmp2->data)              //(data < tmp2->data) 오름차순 정렬
            break;               //(data > tmp2->data)   내림차순 정렬
        tmp1 = tmp2;
        tmp2 = tmp2->next;
    }
    tmp1->next = (Node *)malloc(sizeof(Node));
    tmp1->next->data = data;
    tmp1->next->next = tmp2;
}    
 
void deleteNode(LList *list, int data)
{
    Node *tmp1 = list->p;
    Node *tmp2 = list->p->next;
    
    while(tmp2->data !=data)
    {
        tmp1 = tmp2;
        tmp2 = tmp2->next;
    }
    
    tmp1->next = tmp2->next;
    free(tmp2);
}
 
int main(void)
{
    LList list;
    initList(&list);
    
    insertNode(&list, 10);
    insertNode(&list, 20);
    insertNode(&list, 30);
    insertNode(&list, 40);
    
    printList(&list);
    
    insertNode(&list, 15);
    printList(&list);
    
    deleteNode(&list, 30);
    printList(&list);
    
    cleanupList(&list);
 
    return 0;
}
 


함수포인터를 사용해 임의의 데이터 오름차순 내림차순 정렬로 변경해보기



Posted by 차희빈

차희빈

달력