Cod sursa(job #935234)

Utilizator George515600Bejan George George515600 Data 2 aprilie 2013 12:52:05
Problema Hashuri Scor 100
Compilator c Status done
Runda Arhiva educationala Marime 2.59 kb
#include <stdio.h>
#include <stdlib.h>


#define M 93911
typedef struct DLLNode
{
    int data;
    struct SLLNode* next;
    struct SLLNode* prev;
} DLLNode;

typedef struct
{
    struct DLLNode* first;
    struct DLLNode* last;
    int size;
} DLList;


int hashFunction(int n)
{
    return n%M;}



DLList* createDLList()
{
    DLList* p = (DLList*)malloc(sizeof(DLList));
    if (p)
    {
        p->first = NULL;
        p->last = NULL;
        p->size = 0;
    }
    return p;
}

DLLNode* createDLLNode(int key)
{
    DLLNode* p = (DLLNode*)malloc(sizeof(DLLNode));
    if (p)
    {
        p->data = key;
        p->next = NULL;
        p->prev = NULL;
    }
    return p;
}

int insertDLLNode(DLList* list, DLLNode* value)
{
    if (!list || !value) return 0;
    if (list->size < 1)
    {
        list->first = value;
        list->last = value;
        list->size++;
    }
    else
    {
        DLLNode* j = list->last;
        j->next = value;
        value->prev = j;
        list->last = value;
        list->size++;
    }
}

DLLNode* findNode(DLList* L, int node)
{
    DLLNode* p = L->first;
    while (p && p->data != node)
        p = p->next;
    return p;
}

int removeNode(DLList* L, int node)
{
    DLLNode* p = findNode(L, node);
    if (p)
        if (p == L->first)
        {
            L->first = p->next;
            L->size--;
            return 1;
        }
        else if (p == L->last)
        {
            L->last = p->prev;
            L->last->next = NULL;
            L->size--;
            return 1;
        }
        else
        {
            DLLNode* j = p->prev;
            DLLNode* i = p->next;
            j->next = i;
            i->prev = j;
            L->size--;
            return 1;
        }

    else
        return 0;
}

DLList* HashTable[M];

int main()
{
    FILE *f = fopen("hashuri.in","r");
    FILE *g = fopen("hashuri.out","w");

    int ops, ord, nr, valueToAdd,valueToDelete;
    int i;
    for(i = 0; i < M; i++)
        HashTable[i] = createDLList();
    fscanf(f,"%d", &ops);
    for (i = 0; i < ops; i++)
    {
        fscanf(f,"%d %d",&ord, &nr);
        if (ord == 1)
            if (!findNode(HashTable[hashFunction(nr)], nr))
            {
                valueToAdd = hashFunction(nr);
                insertDLLNode(HashTable[valueToAdd], createDLLNode(nr));
            }
        if (ord == 2)
            removeNode(HashTable[hashFunction(nr)], nr);
        if (ord == 3)
            if (findNode(HashTable[hashFunction(nr)], nr))
                fprintf(g,"1 \n");
            else
                fprintf(g,"0 \n");
    }

    fclose(f);
    fclose(g);
    return 0;
}