-
Notifications
You must be signed in to change notification settings - Fork 2
/
linkedListDeletionChallenge.c
109 lines (87 loc) · 1.97 KB
/
linkedListDeletionChallenge.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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
/*
* Challenge #2 from Platzi's C course
* I modified mchojrin's code for it to enable deletion of a node according to
* user input
* @author J. Alvarez and mchojrin from Platzi
*/
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int number;
struct Node * next;
} NODE;
NODE * createNode( int number )
{
NODE * newNode;
newNode = malloc( sizeof(NODE) );
newNode->next = NULL;
newNode->number = number;
return newNode;
}
NODE * deleteNode( NODE * list, int number ) {
NODE * aux = list;
if (aux->number == number) {
list = aux->next;
free(aux);
}
else {
while(aux->next->number != number)
aux = aux->next;
NODE * toDelete = aux->next;
aux->next = aux->next->next;
free(toDelete);
}
return list;
}
int main( int argc, const char * arg[] )
{
NODE * start = NULL, * current, *next;
char goOn;
int listSize = 0, number;
do {
printf( "La lista contiene %d nodos. Ingrese el siguiente numero (0 para finalizar)\n", listSize );
scanf("%d", &number );
if ( number ) {
if ( !start ) {
start = createNode( number );
listSize++;
} else {
current = start;
while ( current->next ) {
current = current->next;
}
current->next = createNode( number );
listSize++;
}
goOn = 1;
} else {
goOn = 0;
}
} while ( goOn );
current = start;
printf( "La lista contiene los numeros: \n" );
while (current) {
printf( "%d", current->number );
printf( current->next ? ", " : "\n" );
current = current->next;
}
int nodoABorrar;
printf("Por favor ingrese el numero de nodo a borrar: ");
scanf("%d",&nodoABorrar);
printf("Vamos a borrar el nodo con numero %d\n",nodoABorrar);
start = deleteNode(start,nodoABorrar);
current = start;
printf( "La lista queda asi: \n" );
while (current) {
printf( "%d", current->number );
printf( current->next ? ", " : "\n" );
current = current->next;
}
current = start;
while (current) {
next = current->next;
free( current );
current = next;
}
return 0;
}