Exemple #1
0
int enqueue(list* listPtr,int priority,void* data){
	Node* nodePtr = calloc(sizeof(Node),1);
	Node *temp=calloc(sizeof(Node),1);
	Node *temp2=calloc(sizeof(Node),1);
	if(listPtr->length == 0){
		return createFirstNode(nodePtr,listPtr,data,priority);
	}
	else{
		createNode(nodePtr,data,priority);
		temp = listPtr->head;
		if(temp->priority > nodePtr->priority)
			return insertFirst(nodePtr,temp,listPtr);
		while(temp->next!=NULL)
			temp= temp->next;	
		if(temp->priority < nodePtr->priority)
			return insertLast(temp,nodePtr,listPtr);
		temp = listPtr->head;
		while(temp->priority < nodePtr->priority){
			temp2=temp;
			temp=temp->next;
		}
		temp2->next = nodePtr;
		nodePtr->next=temp;
		listPtr->length +=1;
		return 1;	
	};
}
void insertAtPosition(node **head, int data, int pos)
{
	int len = size(head);
	if (pos <= 0 || pos > (len + 1))
	{
		printf("Position is not Valid\n");
		return;
	}
	if(pos == 1)
	{
		insertFirst(head,data);
	}
	else if(pos == (len +1))
	{
		insertLast(head, data);
	}
	else
	{
		// execution reach in this location if position is between 2 and len
		node *newNode = createNode(data);
		node *curr = (*head)->next;
		node *prev = *head;
		int i = 2;	// start from 2nd node
		while(i != pos)
		{
			i ++;
			prev = curr;
			curr = curr->next;
		}
		newNode->next = curr;
		prev->next = newNode;
	}
	// size++;
}
Exemple #3
0
void insert(int index, char* word) {
    if (hashtable[index] == NULL) {
        hashtable[index] = insertFirst(word);
    }else {
        hashtable[index] = insertInPlace(hashtable[index], word);
    }
}
Exemple #4
0
//inserts a Partial Path into a list in it's sorted position (sorted by costtonode/f-cost (depending on algorithm)) Insertion sort for each insertion should be O(N).
void insertSorted(LinkedList* list, Solution* sol)
{
	LinkedListNode* node = list->head;
	LinkedListNode* replace; //spot to replace
	int foundspot = 0;
	while ((node != NULL) && (!foundspot))
	{
		if ( ((Solution*)(node->data))->cost > sol->cost)
		{

			foundspot = 1;
			replace = node->prev;
            //if it's the smallest node
			if (replace == NULL)
				insertFirst(list,sol);
			else
			{
            //if it is in the middle somewhere
				LinkedListNode *newLLN = (LinkedListNode*)malloc(sizeof(LinkedListNode));
				newLLN->data = (void*)sol;
				newLLN->next = replace->next;
				newLLN->prev = replace;
				replace->next = newLLN;
				newLLN->next->prev = newLLN;
                (list->len)++;
			}
		}
		node = node->next;
	}
    //if it is the largest node
	if (!foundspot)
		insertLast(list, sol);
}
void eventbus_register(String address,void (*func)(String *)){
    handler_t handler;
    handler.address=address;
    handler.function=func;
	
    if(find(address)==false){
        jsonMessage_t js;
        js.address=address;
        js.type="register";
		js.replyAddress=NULL;
        JSON_Value *body = json_parse_string(NULL);
        JSON_Value *headers = json_parse_string(NULL);

        js.body=body;
        js.headers=headers;
        String message=NULL;
        getMessage(js,&message);
		
        send_frame(&message);
	
        free(message);
    }
    insertFirst(node_index,handler);
    node_index++;
}
void insertEnd(LIST_HEAD *list, NODE *newNode) {
    if (list->tail == NULL) {
        insertFirst(list, newNode);
    } else {
        insertAfter(list, list->tail, newNode);
    }
}
Exemple #7
0
int main(void) {

	struct node *head = NULL ;
	insertFirst(&head, 10);
	insertFirst(&head, 22);
	insertFirst(&head, 35);
	insertFirst(&head, 75);

	printf("Original List is \n");
	printList(head);

	printf("\nPrinting the list in reverse order\n");
	printReverse(head);


}
Exemple #8
0
void insVFirst(List &L, Peserta PNew){
	address P=alokasi(PNew);
	if(alokasiSukses(P))
	{
		insertFirst(L,P);
	}
}
Exemple #9
0
listaCurso *abreFicheiro(listaCurso *LC){
	Pessoa *nv=NULL,*P=NULL;
	ArvoreAB *nvA=NULL, *A=NULL;
    	listaCurso *aux=LC, *nvC=NULL;
    	int x,eq;
	FILE *fp=fopen("est_dados_14_15.txt","r");
	if(fp==NULL){
		printf("Erro na abertura do ficheiro.\n");
		exit(1);
	}
	while(!feof(fp)){
        	nv=makeNode();
		if(fscanf(fp,"%d/%d/%d;%d;%d;%d",&nv->dia,&nv->mes,&nv->ano,&nv->bi,&nv->curso,&nv->nota)!=0){
            		aux=existe(aux,nv->curso);	
			if(aux==NULL){
				nvC=makeNodeC();
				nvC->curso=nv->curso;
				LC=insertLista(LC,nvC);
				aux=LC;
			}
            		nvA=makeNodeAB();
			nvA->nota=nv->nota;
			nvA->lista=insertFirst(nvA->lista,nv);
			aux->AB=insereAB(aux->AB,nvA);
			eq=equilibrada(aux->AB);
			if(abs(eq)>1)	aux->AB=equilibra(aux->AB,eq);
			aux=LC;	
		}
	}
	fclose(fp);
	return (aux);
}
Exemple #10
0
int main(void) {

	struct node *head = NULL ;
	insertFirst(&head, 10);
	insertFirst(&head, 22);
	insertFirst(&head, 35);
	insertFirst(&head, 75);

	     printf("Original Linked list \n");
	     printList(head);
	     reverseRecursive(&head);
	     printf("\nReversed Linked list \n");
	     printList(head);
	     getchar();

}
Exemple #11
0
void insertID (List &L2, address P) {
    address Q=First(L2);
    if (Q==NULL) {
        insertFirst(L2,P);
    }
    else if(Info(P).ID < Info(Q).ID) {
        insertFirst(L2,P);
    }
    else {
        do{
            if (Info(Next(Q)).ID > Info(P).ID) {
                break;
            }
            Q=Next(Q);
        } while(Info(P).ID > Info(Q).ID && Next(Q)!= First(L2));
        insertAfter(L2,P,Q);
    }
}
Exemple #12
0
Pessoa *procuraNota(ArvoreAB *A, int nota, char symbol, Pessoa *p){
	Pessoa *nv=NULL;
	if(A==NULL)	return p;
	if(symbol=='+'){
		if(nota>A->nota){
			p=procuraNota(A->fd,nota,symbol,p);
			return p;
		}
		if(nota==A->nota){
			p=procuraNota(A->fd,nota,symbol,p);
			return p;
		}
		p=procuraNota(A->fe,nota,symbol,p);
		while(A->lista!=NULL){
			nv=makeNode();
			nv->bi=A->lista->bi;
			if(exists(p,nv->bi)!=1)
				p=insertFirst(p,nv);
			A->lista=A->lista->nseg;
		}
		p=procuraNota(A->fd,nota,symbol,p);
		return p;
	}
	if(symbol=='-'){
		if(nota<A->nota){
			p=procuraNota(A->fe,nota,symbol,p);
			return p;
		}
		if(nota==A->nota){
			p=procuraNota(A->fe,nota,symbol,p);
			return p;
		}
		p=procuraNota(A->fd,nota,symbol,p);
		while(A->lista!=NULL){
			nv=makeNode();
			nv->bi=A->lista->bi;
			if(exists(p,nv->bi)!=1)
				p=insertFirst(p,nv);
			A->lista=A->lista->nseg;
		}
		p=procuraNota(A->fe,nota,symbol,p);
		return p;
	}
}
int main(void)
{
    initializeList();
    while(1)
    {
        printf("1. Insert new item. 2. Delete item. 3. Search item. \n");
        printf("4. Insert Last. 5. Delete Last. 6. Print forward. \n");
        printf("7. Print backward. 8. exit.\n");

        int ch;
        scanf("%d",&ch);
        if(ch==1)
        {
            int item;
            scanf("%d", &item);
            insertFirst(item);
        }
        else if(ch==2)
        {
            int item = deleteLast();
            if(item!=NULL_VALUE) printf("Deleted: %d\n", item);
        }
        else if(ch==3)
        {
            int item;
            scanf("%d", &item);
            struct listNode * res = searchItem(item);
            if(res!=0) printf("Found.\n");
            else printf("Not found.\n");
        }
        else if(ch==4)
        {
            int item;
            scanf("%d",&item);
            insertLast(item);
        }
        else if(ch==5)
        {
            deleteLast();
        }
        else if(ch==6)
        {
            printListForward();
        }
        else if(ch==7)
        {
            printListBackward();
        }
        else if(ch==8)
        {
            freeall(list);
            break;
        }
    }

}
Exemple #14
0
int DList_insertData(DList* list , int index , void* data){
    Node* node = calloc(1,sizeof(node));
    if (index > list->length) return 0;
    if (index == 0)   insertFirst(list,node);
    else if(index == list->length)   insertLast(list,node);
    else insertMiddle(list, index, node);
    node->data = data;
    list->length++;
    return 1;
};
Exemple #15
0
void main(int argc, char * argv[])
{	
	int i, test, vyska;
	float vaha, vek;
	char * jmeno;
	FILE *jm_soub;
	tClovek searchTest={0,0,0,"Matej Kocour"}, nacti[5];
	tUkDbClovek db=NULL, tmpUk;

	if (argc >=2)
	{
		if( (jm_soub = fopen(argv[1], "r")) == NULL) {
			fprintf(stderr, "Soubor %s se nepodarilo otevrit.\n", argv[1]);
			printf("Soubor %s se nepodarilo otevrit.\n", argv[1]);
			exit(1);
		}
			else {
				jm_soub = fopen(argv[1], "r");
				for(i=0; i<5; i++) {				
					fscanf(jm_soub, "%i %.1f %.1f %s\n", &nacti[i].vyska, &nacti[i].vaha, &nacti[i].vek, &nacti[i].jmeno);				
				}			
				fclose(jm_soub);
				printf("\nNacteni informaci ze souboru dokonceno");
			}
		
		db=insertFirst(db, nacti[0]);
		db=insertFirst(db, nacti[1]);
		db=insertLast(db, nacti[2]);
		db=insert(db, nacti[3]);
		db=insert(db, nacti[4]);
		printf("\nInformace ulozeny do seznamu");
		tmpUk=search(db, nacti[2]);
		if (tmpUk!=NULL && tmpUk->clovek.jmeno!=NULL) printf("Found: %s\n", tmpUk->clovek.jmeno);
		tmpUk=search(db, searchTest);
		if (tmpUk!=NULL && tmpUk->clovek.jmeno!=NULL) printf("Found: %s\n", tmpUk->clovek.jmeno);
		db=deleteLast(db);
		db=deleteAny(db);
		while ((db=deleteFirst(db))!=NULL); /* smazani celeho seznamu */
		printf("\nSeznam je smazan");
	}
	else printf("parametr \"jmeno souboru\" nebyl zadan!\n");
}
Exemple #16
0
void insertName(List &L2, address P) {
    address Q;
    Q=First(L2);
    if(Q==NULL) {
        insertFirst(L2,P);
    }
     else if(Info(P).name < Info(Q).name) {
        insertFirst(L2,P);
    }
    else {
        while (Info(P).name > Info(Q).name && Next(Q)!= First(L2)) {
            if (Info(Next(Q)).name > Info(P).name) {
                break;
            }
            Q=Next(Q);
        }
        insertAfter(L2,P,Q);
    }

}
Exemple #17
0
void List<T>::VlozNaslednika(const T& prvek)
{
    if (!insertFirst(prvek))
    {
        Node* newLast = new Node();
        newLast->_data = prvek;
        newLast->_next = _actual->_next;
        _actual->_next = newLast;
        _actual = newLast;
        _count++;
    }
}
// int size = 0;
int main()
{
	//Initialize Crcular linked list with NULL head
	node *head = NULL;
	int data = 10;
	// printf("Enter: ");
	// scanf("%d",&data);
	insertLast(&head, data);
	insertFirst(&head, 5);
	print(&head);
	printf("Size: %d\n", size(&head));

	printf("Insert at position 1\n");
	insertAtPosition(&head, 1,1);
	print(&head);
	printf("Size: %d\n", size(&head));

	printf("Insert at position 4\n");
	insertAtPosition(&head, 15,4);
	print(&head);
	printf("Size: %d\n", size(&head));

	deleteFirst(&head);
	print(&head);
	printf("Size: %d\n", size(&head));	

	deleteLast(&head);
	print(&head);
	printf("Size: %d\n", size(&head));	

	deleteAtPosition(&head,2);
	print(&head);
	printf("Size: %d\n", size(&head));	

	deleteAtPosition(&head,1);
	print(&head);
	printf("Size: %d\n", size(&head));	

	printf("New Circular linked list\n");
	node *head1 = NULL;
	createList(&head1);
	print(&head1);

	printf("Enter data want to search: ");
	scanf("%d", &data);
	search(&head1,data);

	printf("Sort a circular linked list\n");
	sort(&head1);
	print(&head1);

}
Exemple #19
0
int main(int argc, char* argv[]){  
    Point p1;
    p1.x = 1; p1.y = 2;  
    Point p2;
    p2.x = 3; p2.y = 4; 
    
    List list = initList(sizeof(Point));
    insertFirst(list, &p1);
    insertFirst(list, &p2);  
    
    Point* test[2];
    test[0] = (Point*) removeFirst(list);
    test[1] = (Point*) removeFirst(list);
     
    /*
    printf("p2.x: %d, p2.y: %d\n", test[0]->x, test[0]->y);
    printf("p1.x: %d, p1.y: %d\n", test[1]->x, test[1]->y);
    */
    liberer(list);
    
    return !(test[0]->x==3 && test[0]->y==4 && test[1]->x==1 && test[1]->y==2);
}
// copy constructor
DoublyLinkedList::DoublyLinkedList(const DoublyLinkedList& dll)  //O(n)
{
  // Initialize the list
  header.next = &trailer; trailer.prev = &header;
  
  DListNode *current = dll.getFirst();
  while(current != dll.getAfterLast())
	{
	  insertFirst(current->getElem());
	  current=current->getNext();
	}
  
}
Exemple #21
0
void List<T>::VlozPrvni(const T& prvek)
{
    if (!insertFirst(prvek))
    {
        Node* novy = new Node();
        novy->_data = prvek;
        novy->_next = _head;
        _head = novy;
        _last->_next = _head;
        _actual = novy;
        _count++;
    }
}
Exemple #22
0
void List<T>::VlozPosledni(const T& prvek)
{
    if (!insertFirst(prvek))
    {
        Node* oldLast = _last;
        Node* newLast = new Node();
        newLast->_data = prvek;
        newLast->_next = _head;
        _last = newLast;
        oldLast->_next = newLast;
        _actual = _last;
        _count++;
    }
}
Exemple #23
0
void insertLast(List &L, address P){
	address temp;
	if(isEmpty(L))
	{
		insertFirst(L,P);
	}
	else
	{
		temp=findLast(L);
		temp->Next=P;
		P->Next=L.First;
		
	}
}
Exemple #24
0
void insertLast(List &L, address P)
{
    if(First(L) == NULL)
    {
        insertFirst(L,P);
    }
    else
    {
        Next(P) = First(L);
        Prev(P) = Last(L);
        Next(Last(L))=P;
        Prev(Last(L)) = P;
        Last(L) = P;
    }
}
// assignment operator
DoublyLinkedList& DoublyLinkedList::operator=(const DoublyLinkedList& dll) //O(n)
{
	
	while (!isEmpty()){
		removeFirst();
	} 
  
    header.next = &trailer; trailer.prev = &header;
    DListNode *current = dll.getFirst();
    while(current != dll.getAfterLast())
	{
  	  insertFirst(current->getElem());
	  current=current->getNext();
    }
	
	return *this;
}
Exemple #26
0
void insertData(List &L) {
    address P;
    infotype x;

    cout<<"Masukkan ID yang ingin anda masukkan untuk di cek : ";
    cin>>x.id;
    cout<<"Masukkan nama yang ingin anda masukkan untuk di cek : ";
    cin>>x.nama;
    cout<<endl;
    P = findElm(L,x);
    if (P == NULL) {
        cout<<"Data belum ada "<<endl;
        inputData(x);
        P=alokasi(x);
        insertFirst(L,P);
    }
    else {
        cout<<"Data sudah ada"<<endl;
    }
}
Exemple #27
0
Pessoa *ordena(Pessoa *p){
	Pessoa *aux,*LO=NULL;
	while(p!=NULL){
		aux=findLargest(p);
		if(aux->nant==NULL){
			p=p->nseg;
			if(p!=NULL)	p=p->nseg;
			aux->nseg=NULL;
		}
		if(aux->nseg==NULL){
			aux->nant->nseg=NULL;
			aux->nant=NULL;
		}
		else{
			aux->nant->nseg=aux->nseg;
			aux->nseg->nant=aux->nant;
			aux->nseg=NULL;
			aux->nant=NULL;
		}
		LO=insertFirst(LO,aux);
	}
	return LO;
}
int main(int argc, char **argv) {
    // 매개변수 1:자기포트 2:서버IP 3:서버포트 4:자기ID
    int tcpServ_sock;
    
    struct sockaddr_in tcpServer_addr;
    struct sockaddr_in newTcp_addr;
    
    fd_set reads, temps;
    int fd_max;
    
    char command[1024];
    
    if(argc != 5){
        printf("Usage : %s <myport> <serverIP> <serverport> <myID>\n", argv[0]);
        exit(1);
    }
    
    display();
    
    if ((tcpServ_sock = socket(PF_INET, SOCK_STREAM, 0)) < 0) {
        perror("socket");
        exit(1);
    }// creating socket descriptor for tcp
    
    memset((void *) &tcpServer_addr, 0, sizeof (tcpServer_addr));
    tcpServer_addr.sin_family = AF_INET;
    tcpServer_addr.sin_addr.s_addr = INADDR_ANY;
    tcpServer_addr.sin_port = htons((u_short)atoi(argv[1])); // portnum
    fd_max = 10;
    
    if (bind(tcpServ_sock, (struct sockaddr *)&tcpServer_addr, sizeof (tcpServer_addr)) < 0) {
        perror("bind error");
        exit(1);
    } // bind
    
    if (listen(tcpServ_sock, SOMAXCONN) < 0) {
        perror("listen");
        exit(1);
    } // wait connect
    
    // 여기까지 기본 소켓세팅
    hostIP = argv[2]; // ip
    hostport = argv[3]; // port numbere
    myID = argv[4];
    char buf[1024];
    strcat(buf, "@connect ");
    strcat(buf, myID);
    //peertcpSockets = connectToServer(buf);
    peertcpSockets = connectToServer(buf);
    
    FD_ZERO(&reads);
    FD_SET(fileno(stdin), &reads);
    FD_SET(tcpServ_sock, &reads);
    FD_SET(peertcpSockets, &reads);
    while(1){
        int nfound;
        temps = reads;
        nfound = select(fd_max+1, &temps, 0, 0, NULL);
        // nfound?
        if(FD_ISSET(fileno(stdin), &temps)) {
            // Input from the keyboard
            char sendhttp[1024];
            memset(sendhttp, NULL, sizeof(sendhttp));
            
            
            fgets(command, sizeof (command), stdin);
            
            if( command[0] == '@' ){
                // send to server
                if(command[1] == 'e'){ // when exit
                    head = NULL;
                    peertcpSockets = connectToServer(command);
                    close(peertcpSocket);
                    exit(1);
                }
                peertcpSockets = connectToServer(command);
                FD_SET(peertcpSockets, &reads);
                // exit했을때는 나에게 들어있는 유저목록 다 지워야한다.
            }else{
                node* cnode = head;
                char sendmsg[1024];
                strcat(sendmsg, myID);
                strcat(sendmsg, ") ");
                strcat(sendmsg, command);
                
                while(cnode != NULL){
                    peertcpSockets = connectToClient(head->IP, toArray(head->port), sendmsg);
                    close(peertcpSockets);
                    cnode = cnode->next;
                } // 유저에게 메시지 전송
                close(peertcpSocket);
            }
            fflush(stdin);
        }else if(FD_ISSET(tcpServ_sock, &temps)){
            int addrlen;
            addrlen = sizeof(newTcp_addr);
            peertcpSockets = accept(tcpServ_sock, (struct sockaddr *)&newTcp_addr, (unsigned int*)&addrlen);
            //printf("connection from host %s, port %d, socket %d\n\n",
            //       inet_ntoa(newTcp_addr.sin_addr), ntohs(newTcp_addr.sin_port), peertcpSocket);
            if (peertcpSockets < 0) {
                perror("accept");
                exit(1);
            }
            FD_SET(peertcpSockets, &reads);
            // make connection
        }else if(FD_ISSET(peertcpSockets, &temps)){ // 서버에서 응답받은 내용
            char buf[1024];
            memset(buf, NULL, sizeof(buf));
            read(peertcpSockets, buf, sizeof(buf));
            char tbuf[1024];
            strcpy(tbuf, buf);
            
            char* inif = strtok(tbuf, "\n");
            
            if(!strcmp(touppers(inif),"JOIN")){
                char* temp;
                temp = strtok(buf, "\n");
                printf("%s\n", temp); // 입력받은 첫줄 출력
                
                while((temp = strtok(NULL, "\n")) != NULL){
                    char* tempIP = strtok(temp, " ");
                    char* tempPort = strtok(NULL, " ");
                    int tport = atoi(tempPort);
                    char* tempID = strtok(NULL, " ");
                    insertFirst(tempIP, tport, tempID, 0);
                }
                close(peertcpSockets);
            }else if(!strcmp(touppers(inif),"INVITE OK")){
                printf("%s\n", inif);
                char* temp;
                temp = strtok(NULL, "\n");
                char* tempIP = strtok(temp, " ");
                char* tempPort = strtok(NULL, " ");
                char* tempID = strtok(NULL, " ");
                
                printf("invite %s\n", tempID);
                int tport = atoi(tempPort);
                insertFirst(tempIP, tport, tempID, 0);
                close(peertcpSockets);
                // invite에 성공했다면 그사람을 저장한다.
            }else if(!strcmp(touppers(inif),"@ADD")){
                printf("%s\n", inif);
                char* tempIP = strtok(NULL, " ");
                char* tempPort = strtok(NULL, " ");
                char* tempID = strtok(NULL, " ");
                
                int tport = atoi(tempPort);
                insertFirst(tempIP, tport, tempID, 0);
                close(peertcpSockets);
                // close 소켓 서버에서?유저에서?
            }else if(!strcmp(touppers(inif),"@DELETE")){
                printf("%s\n", inif);
                char* tempIP = strtok(NULL, " ");
                char* tempPort = strtok(NULL, " ");
                int tport = atoi(tempPort);
                deletes(tempIP, tport);
                close(peertcpSockets);
            }else{
                printf("%s\n",buf); // print receive msg
                close(peertcpSockets);
                //FD_CLR(peertcpSockets, &reads);
            }
            buf[0] = '\0';
            printf("> ");
        }// receive
        
        fflush(stdout);
    }
}//main End
int main(int argc, char *argv[]){
    
    struct sockaddr_in server;
    int new_sock, server_sock = -1;
    int addrlen;
    char command[128], buf[128];
    
    if (argc != 2) {
        (void) fprintf(stderr,"usage: %s port# \n",argv[0]);
        exit(1);
    }
    
    portnum = atoi(argv[1]);
    
    // Create a Server Socket
    if((server_sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0){
        perror("socket");
        exit(1);
    }
    
    memset((void*)&server, 0, sizeof(server));
    server.sin_family = AF_INET;
    server.sin_addr.s_addr = INADDR_ANY;
    server.sin_port = htons((u_short)atoi(argv[1]));
    
    if(bind(server_sock, (struct sockaddr *)&server, sizeof server) < 0) {
        perror("bind");
        exit(1);
    }
    
    if(listen(server_sock, SOMAXCONN) < 0) {
        perror("listen");
        exit(1);
    }
    
    
    
    //
    //
    //
    while(1){
        // Input from the keyboard
        memset(command, 0x00, sizeof command);
        
        addrlen = sizeof server;
        new_sock = accept(server_sock,
                          (struct sockaddr *)&server,
                          (socklen_t *)&addrlen);
        
        if (new_sock < 0) {
            perror("accept");
            exit(1);
        }
        
        printf("connection : Host IP %s, Port %d, socket %d\n",
               inet_ntoa(server.sin_addr), ntohs(server.sin_port), new_sock);
        
        read(new_sock, command, sizeof command);	// read user command
        printf("%s", command);
        
        if(!strncmp(command, "@quit", 5)){			// quit
            memset(buf, 0x00, sizeof(buf));
            
            strcat(buf, "@delete ");
            strcat(buf, inet_ntoa(server.sin_addr));
            strcat(buf, " ");
            strcat(buf, toArray(ntohs(server.sin_port)));
            
            struct node* delNode = find(inet_ntoa(server.sin_addr), ntohs(server.sin_port));
            int roomNum = delNode->room;
            delNode->room = 0;
            
            current = head;
            while(current != NULL){
                if(current->room == roomNum)
                    connectToClient(current->IP, toArray(current->port), buf);
                current = current->next;
            }
        }
        else if(!strncmp(command, "@exit", 5)){		// exit
            memset(buf, 0x00, sizeof(buf));
            
            strcat(buf, "@delete ");
            strcat(buf, inet_ntoa(server.sin_addr));
            strcat(buf, " ");
            strcat(buf, toArray(ntohs(server.sin_port)));
            strcat(buf, "\n");
            
            int roomNum = find(inet_ntoa(server.sin_addr), ntohs(server.sin_port))->room;
            deletes(inet_ntoa(server.sin_addr), ntohs(server.sin_port));
            if(roomNum != 0){
                current = head;
                while(current != NULL){
                    if(current->room == roomNum)
                        connectToClient(current->IP, toArray(current->port), buf);
                    current = current->next;
                }
            }
        }
        else if(!strncmp(command, "@connect", 8)){	// connect
            insertFirst(inet_ntoa(server.sin_addr), ntohs(server.sin_port), &command[9], 0);
            printf("%s is connected\n", &command[9]);
            
            if (write(new_sock, "connection ok", strlen("connection ok")) < 0) {
                perror("write");
                exit(1);
            }
        }
        else if(!strncmp(command, "@getlist", 8)){		// user & room list
            memset(buf, 0x00, sizeof(buf));
            for(int i=0; i<room_size; i++){
                if(i == 0){
                    strcat(buf, "\n==========waiting room ");
                    strcat(buf, "==========\n");
                }
                else{
                    strcat(buf, "==========room# ");
                    strcat(buf, toArray(i));
                    strcat(buf, "==========\n");
                }
                
                current = head;
                while(current != NULL){
                    if(current->room == i){
                        strcat(buf, current->IP);
                        strcat(buf, " ");
                        strcat(buf, toArray(current->port));
                        strcat(buf, " ");
                        strcat(buf, current->ID);
                        strcat(buf, "\n");
                    }
                    current = current->next;
                }
            }
            
            if (write(new_sock, buf, strlen(buf)) < 0) {
                perror("write");
                exit(1);
            }
        }
        else if(!strncmp(command, "@mkroom", 7)){	// mkroom
            room_size++;
            memset(buf, 0x00, sizeof(buf));
            strcat(buf, "room ");
            strcat(buf, toArray(room_size));
            strcat(buf, " is created\n");
            
            if (write(new_sock, buf, strlen(buf)) < 0) {
                perror("write");
                exit(1);
            }
        }
        else if(!strncmp(command, "@join", 5)){		// join
            int roomNum = atoi(&command[6]);
            
            memset(buf, 0x00, sizeof(buf));
            strcat(buf, "@add ");
            strcat(buf, inet_ntoa(server.sin_addr));
            strcat(buf, " ");
            strcat(buf, toArray(ntohs(server.sin_port)));
            strcat(buf, "\n");
            
            char join[1024];
            memset(join, 0x00, sizeof(join));
            strcat(join, "@join\n");
            
            int i = 0;
            current = head;
            while(current != NULL){
                if(strcmp(toArray(ntohs(server.sin_port)), toArray(current->port)) && current->room == roomNum){
                    connectToClient(current->IP, toArray(current->port), buf);
                    strcat(join, current->IP);
                    strcat(join, " ");
                    strcat(join, toArray(current->port));
                    strcat(join, " ");
                    strcat(join, current->ID);
                    strcat(join, "\n");
                }
                current = current->next;
            }
            
            if (write(new_sock, join, strlen(join)) < 0) {
                perror("write");
                exit(1);
            }
            find(inet_ntoa(server.sin_addr), ntohs(server.sin_port))->room = atoi(&command[6]);
            printf("room to %d\n", atoi(&command[6]));
            printf("room to %d\n", atoi(&command[6]));
        }
    }
}// main
Exemple #30
0
int main()
{
    int pil;
    infotype x, y;
    address P, Q;
    list L;
    createList(&L);

    while(pil != 10) {
        cout<<"1. Insert first"<<endl;
        cout<<"2. Insert after"<<endl;
        cout<<"3. Insert last"<<endl;
        cout<<"4. Delete first"<<endl;
        cout<<"5. Delete after"<<endl;
        cout<<"6. Delete last"<<endl;
        cout<<"7. View list"<<endl;
        cout<<"8. Search element"<<endl;
        cout<<"9. Search sentinel"<<endl;
        cout<<"Pilih: ";
        cin>>pil;

        switch(pil) {

        case 1:
            cout<<"ID           : ";
            cin>>x.id;
            cout<<"Nama         : ";
            cin>>x.nama;
            cout<<"Jabatan      : ";
            cin>>x.jabatan;
            cout<<"Departemen   : ";
            cin>>x.departemen;
            cout<<"Gaji         : ";
            cin>>x.gaji;

            P = allocate(x);
            insertFirst(&L, P);
            cout<<endl;
            cout<<"Insert complete.";
            break;

        case 2:
            cout<<"ID           : ";
            cin>>x.id;
            cout<<"Nama         : ";
            cin>>x.nama;
            cout<<"Jabatan      : ";
            cin>>x.jabatan;
            cout<<"Departemen   : ";
            cin>>x.departemen;
            cout<<"Gaji         : ";
            cin>>x.gaji;

            cout<<"Dimasukan setelah ID: ";
            cin>>y.id;
            if(searchElement(&L, y) != Nil) {
                insertAfter(&L, allocate(x), allocate(y));
                cout<<endl;
                cout<<"Insert complete.";
            } else {
                cout<<"Data tidak ada.";
            }
            break;

        case 3:
            cout<<"ID           : ";
            cin>>x.id;
            cout<<"Nama         : ";
            cin>>x.nama;
            cout<<"Jabatan      : ";
            cin>>x.jabatan;
            cout<<"Departemen   : ";
            cin>>x.departemen;
            cout<<"Gaji         : ";
            cin>>x.gaji;

            insertLast(&L, allocate(x));
            cout<<endl;
            cout<<"Insert complete.";

            break;

        case 4:
            cout<<"ID           : ";
            cin>>x.id;
            deleteFirst(&L, allocate(x));
            cout<<endl;
            cout<<"Delete complete.";

            break;

        case 5:
            cout<<"ID: ";
            cin>>x.id;
            P = allocate(x);
            cout<<"Dimasukan setelah ID: ";
            cin>>x.id;
            Q = allocate(x);

            deleteAfter(&L, P, Q);
            cout<<endl;
            cout<<"Delete complete.";

            break;

        case 6:
            cout<<"ID: ";
            cin>>x.id;
            deleteFirst(&L, allocate(x));
            cout<<endl;
            cout<<"Delete complete.";

            break;

        case 7:
            viewList(L);
            break;

        case 8:
            cout<<"ID: ";
            cin>>x.id;
            P = searchElement(&L, x);

            if(P != Nil) {
                cout<<"ID           = "<<info(P).id<<endl;
                cout<<"Nama         = "<<info(P).nama<<endl;
                cout<<"Jabatan      = "<<info(P).jabatan<<endl;
                cout<<"Departemen   = "<<info(P).departemen<<endl;
                cout<<"Gaji         = "<<info(P).gaji<<endl;
            } else {
                cout<<"Data tidak ditemukan.";
            }
            break;
        case 9:
            cout<<"ID: ";
            cin>>x.id;
            P = searchSentinel(&L, x);

            if(P != Nil) {
                cout<<"ID           = "<<info(P).id<<endl;
                cout<<"Nama         = "<<info(P).nama<<endl;
                cout<<"Jabatan      = "<<info(P).jabatan<<endl;
                cout<<"Departemen   = "<<info(P).departemen<<endl;
                cout<<"Gaji         = "<<info(P).gaji<<endl;
            }

            break;
        }
    }
    return 0;
}