This repository has been archived by the owner on Mar 1, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlista_listas_9.c
88 lines (74 loc) · 1.55 KB
/
lista_listas_9.c
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
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define bool int
#define true 1
#define false 0
typedef struct node{
int n;
struct node *next;
}node;
void add (node* head, int v);
node* find_end(node *head);
void list(node *head);
bool troca(node* head, int i1,int i2);
int main(int argc, char const *argv[])
{
node *head = (node*) malloc (sizeof(node));
int t1,t2;
add(head,1);
add(head,2);
add(head,3);
add(head,5);
add(head,12);
add(head,9);
add(head,45);
add(head,-5);
printf("A lista é: \n");
list(head);
printf("Quais elementos quer trocar de posição? \n");
scanf("%d%d",&t1,&t2);
if(troca(head,t1,t2)){
printf("\n--Troca realizada com sucesso--\n");
printf("Nova lista: \n");
list(head);
}
else{
printf("\n--Troca não realizada--\n");
}
return 0;
}
void add (node* head, int v){
node *new = (node*)malloc(sizeof(node));
node *end;
new->n = v;
new->next = NULL;
end = find_end(head);
end->next = new;
}
node* find_end(node *head){
node *count;
for(count = head;count->next!=NULL;count = count->next);
return count;
}
void list(node *head){
node *count;
for(count = head->next;count!=NULL;count = count->next){
printf(" %d ",count->n);
}
}
bool troca(node* head, int i1,int i2){
node *count;
bool ret = true;
for(count = head->next; count!=NULL;count = count->next){
if(count->n == i1){
count->n = i2;
ret = !ret;
}
else if( count->n == i2){//se tudo der certo ret troca de valor duas vezes, então volta a ficar verdadeiro no fim das contas
count->n =i1;
ret = !ret;
}
}
return ret;
}