안선생의 개발 블로그

chaining 본문

알고리즘

chaining

안선생 2022. 11. 27. 16:51

chaining.cpp

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
#include<iostream>
#include "chains.h"
using namespace std;
 
int hash1(int key)
{
    return key % 10;
}
void insert(node* h[], int key)
{
    int index = hash1(key);
    sortedinsert(&h[index], key);
}
int main()
{
    node* ht[10];
    node* temp;
    int i;
    for (i = 0; i < 10; i++)
        ht[i] = NULL;
 
    insert(ht, 12);
    insert(ht, 32);
    insert(ht, 22);
 
    temp = search(ht[hash1(22)], 22);
    cout << temp->data;
    return 0;
}
cs

chains.h

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
#pragma once
struct node
{
    int data;
    node* next;
}; node* first;
 
void sortedinsert(node** h, int x)
{
    node* t, * q = NULL* p =*h;
 
    t = new node;
    t->data = x;
    t->next = NULL;
 
    if (*== NULL)
    
        *= first = t;
 
    else
    {
        while (p && p->data < x)
        {
            q = p;
            p = p->next;
        }
        if (p == first)
        {
            t->next = first;
            first = t;
            *= first;
        }
        else
        {
            t->next = q->next;
            q ->next = t;
        }
    }
}
node* search(node* p, int key)
{
    while (p)
    {
        if (key == p->data)
            return p;
        p = p->next;
            
    }
    return NULL;
}
cs

'알고리즘' 카테고리의 다른 글

graphs  (0) 2022.11.27
hashing  (0) 2022.11.27
sort 정렬  (0) 2022.11.27
heap  (0) 2022.11.27
BST  (0) 2022.11.27