Pagini recente » Cod sursa (job #2493928) | Cod sursa (job #2648358) | Cod sursa (job #1446607) | Cod sursa (job #1140265) | Cod sursa (job #2093733)
#include <stdlib.h>
#include <stdio.h>
struct node {
int data;
struct node *next;
};
int list_add_front(struct node **head, int val)
{
struct node *tmp;
tmp = malloc(sizeof(struct node));
tmp->data = val;
tmp->next = *head;
*head = tmp;
return 0;
}
int list_remove_front(struct node **head)
{
struct node *tmp = *head;
*head = (*head)->next;
free(tmp);
return 0;
}
int list_peek(struct node *head, int *val)
{
*val = head->data;
return 0;
}
int list_remove(struct node **head, int val)
{
struct node **tmp;
struct node *p;
for (tmp = head; *tmp != NULL; tmp = &((*tmp)->next)) {
if((*tmp)->data == val) {
p = *tmp;
*tmp = (*tmp)->next;
free(p);
return 0;
}
}
return 0;
}
int stack_push (struct node **head, int val)
{
return list_add_front(head, val);
}
int stack_pop (struct node **head)
{
return list_remove_front(head);
}
int stack_peek (struct node *head, int* val)
{
return list_peek(head, val);
}
int stack_is_empty (struct node *head) {
return (head == NULL);
}
int main()
{
int n, m;
FILE *infile, *outfile;
int u, v, i;
struct node *st_path = NULL, **list;
int curr;
infile = fopen("ciclueuler.in", "r");
outfile = fopen("ciclueuler.out", "w");
fscanf(infile, "%d %d", &n, &m);
*list = malloc((n+1) * sizeof(struct node*));
for (i = 0; i <=n; i++)
list[i] = NULL;
for (i = 0 ; i < m; i++) {
fscanf(infile, "%d %d", &u, &v);
list_add_front(&list[u], v);
list_add_front(&list[v], u);
}
stack_push(&st_path, 1);
curr = 1;
while (!stack_is_empty(st_path)) {
//while current has edges
while (list[curr] != NULL) {
list_peek(list[curr], &v);
list_remove_front(&list[curr]);
list_remove(&list[v], curr);
curr = v;
stack_push(&st_path, curr);
}
int val;
stack_peek(st_path, &val);
while (list[val] == NULL) {
// don't print first elem again
if(st_path->next != NULL)
fprintf(outfile, "%d ", val);
stack_pop(&st_path);
if (stack_is_empty(st_path))
break;
stack_peek(st_path, &val);
}
// first node that still has unused edges
curr = val;
}
fclose(outfile);
fclose(infile);
}