Deleting node from linked list recursively in C - c

I'm new to C and I'm still having a hard time understanding how pointers and liked lists work, thus I'm having some issues with all of this.
I'm trying to delete a node from a linked list and I'm using the example on this link, but I can't get it to work.
Here's my code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct voos
{
int numeroVoo;
char ciaAerea[20];
char modeloAeronave[20];
char origem[20];
char destino[20];
int qtdeTotalAssentos;
int qtdeAssentosOcupados;
struct voos *proximo;
} *cadastroVoo;
int cont = 0; //Contador temporario para contar numero de assentos ocupados
void addVoo (cadastroVoo *local) //Add item to list
{
cadastroVoo novo;
novo = (cadastroVoo) malloc(sizeof(struct voos));
char temp[20];
if (novo != NULL)
{
printf("Informe o numero do voo: \n");
scanf("%d", &novo->numeroVoo);
printf("Informe a cia aerea: \n");
fflush(stdin);
gets(temp);
strcpy(novo->ciaAerea, temp);
printf("Informe o modelo da aeronave: \n");
fflush(stdin);
gets(temp);
strcpy(novo->modeloAeronave, temp);
printf("Informe a origem do voo: \n");
fflush(stdin);
gets(temp);
strcpy(novo->origem, temp);
printf("Informe o destino do voo: \n");
fflush(stdin);
gets(temp);
strcpy(novo->destino, temp);
cont++;
novo->qtdeAssentosOcupados = cont;
novo->qtdeTotalAssentos = 50;
novo->proximo = *local;
*local = novo;
}
}
void listarVoos(cadastroVoo local) //prints list
{
printf("Imprimindo lista atualizada: \n\n\n");
while (local != NULL)
{
printf("Numero voo: %d\n", local->numeroVoo);
printf("Cia Aerea: %s\n", local->ciaAerea);
printf("Modelo aeronave: %s\n", local->modeloAeronave);
printf("Origem: %s\n", local->origem);
printf("Destino: %s\n", local->destino);
printf("Quantidade total de assentos: %d\n", local->qtdeTotalAssentos);
printf("Quantidade de assentos ocupados: %d\n", local->qtdeAssentosOcupados);
printf("\n");
local = local->proximo;
}
}
cadastroVoo *cancelarPassagem(cadastroVoo *local, int numVoo) //deletes item from list
{
// See if we are at end of list.
if (local == NULL) return NULL;
// Check to see if current node is one to be deleted.
if (local->numeroVoo == numVoo)
{
cadastroVoo *tempNextP;
tempNextP = local->proximo;
free(local);
return tempNextP;
}
// Check the rest of the list, fixing the next pointer in case the next node is the one removed.
local->proximo = cancelarPassagem(local->proximo, numVoo);
//Return the pointer to where we were called from. Since we did not remove this node it will be the same.
return local;
}
int main()
{
cadastroVoo cadastro = NULL;
char op;
while(op != 'f')
{
printf("Escolha a opcao:\n");
printf("a - Incluir voos:\n");
printf("b - Listar voos:\n");
printf("c - Reservar assento em um voo:\n");
printf("d - Cancelar voo:\n");
printf("e - Cancelar passagem:\n");
printf("f - Sair:\n");
op = getche();
printf("\n");
switch(op)
{
case 'a':
{
printf("Incluir voo. \n");
addVoo(&cadastro);
printf("Voo incluso.\n");
break;
}
case 'b':
{
listarVoos(cadastro);
break;
}
case 'c':
{
printf("Reservar assento em um voo. \n");
addVoo(&cadastro);
printf("Assento reservado.\n");
break;
}
case 'd':
{
/**
*while (cancelarVoo != NULL) cancelarVoo()
*/
break;
}
case 'e':
{
int numVoo;
printf("Informe o numero do voo que deseja cancelar a passagem: \n");
scanf("%d", &numVoo);
cancelarPassagem(&cadastro, numVoo);
printf("Passagem cancelada");
break;
}
case 'f': break;
default:
{
printf("Opcao invalida.");
break;
}
}
}
return 0;
}
In the method declaration, if I pass:
cadastroVoo *cancelarPassagem(cadastroVoo *local, int numVoo)
I get the error: request for member 'numeroVoo' in something not a structure or union
But if I pass
cadastroVoo *cancelarPassagem(cadastroVoo local, int numVoo)
It runs, but then when I choose the option that calls this method, I'll get the message on windows that it stopped working.
Does anyone have any idea what could be going wrong?
Thanks in advance.

Probably you are not passing a pointer to the function. I tried your code here and the logic is working fine.
#include <stdio.h>
typedef struct cadastroVoo {
struct cadastroVoo *proximo;
int numero;
} CadastroVoo;
CadastroVoo *cancelarPassagem(CadastroVoo *local, int num);
void inserir(CadastroVoo *cabeca, int num) {
CadastroVoo *p = (CadastroVoo *) malloc(sizeof(CadastroVoo));
p->proximo = cabeca->proximo;
p->numero = num;
cabeca->proximo = p;
}
CadastroVoo *cancelarPassagem(CadastroVoo *local, int num) {
if (local == NULL) return NULL;
printf("> %d\n", local->numero);
printf("> %p\n", local->proximo);
if (local->numero == num) {
CadastroVoo *proximo = local->proximo;
free(local);
return proximo;
}
local->proximo = cancelarPassagem(local->proximo, num);
return local;
}
int main() {
CadastroVoo *cabeca = (CadastroVoo *) malloc(sizeof(CadastroVoo));
cabeca->proximo = NULL;
inserir(cabeca, 10);
inserir(cabeca, 20);
inserir(cabeca, 30);
inserir(cabeca, 40);
inserir(cabeca, 50);
cancelarPassagem(cabeca->proximo, 20);
CadastroVoo *p = cabeca->proximo;
while (p != NULL) {
printf("%d\n", p->numero);
p = p->proximo;
}
}

It is a bad idea to give references instead of the actual code in your question.
Nevertheless here is a simplified demonstrative program that uses recursive methods with a singly linked list. I am sure it does what you need. Investigate it and change your project accordingly.
#include <stdio.h>
#include <stdlib.h>
typedef struct List
{
int data;
struct List *next;
} List;
List * add_node( List *head, int data )
{
if ( head == NULL )
{
head = malloc( sizeof( List ) );
head->data = data;
head->next = NULL;
}
else
{
head->next = add_node( head->next, data );
}
return head;
}
List * remove_node( List *head, int data )
{
if ( head != NULL )
{
if ( head->data == data )
{
List *tmp = head;
head = head->next;
free( tmp );
}
else
{
head->next = remove_node( head->next, data );
}
}
return head;
}
void display_list( List *head )
{
if ( head != NULL )
{
printf( "%d ", head->data );
display_list( head->next );
}
}
int main(void)
{
const int N = 10;
List *head = NULL;
for ( int i = 0; i < N; i++ )
{
head = add_node( head, i );
display_list( head );
printf( "\n" );
}
for ( int i = N; i != 0; i-- )
{
head = remove_node( head, i - 1 );
display_list( head );
printf( "\n" );
}
return 0;
}
The program output is
0
0 1
0 1 2
0 1 2 3
0 1 2 3 4
0 1 2 3 4 5
0 1 2 3 4 5 6
0 1 2 3 4 5 6 7
0 1 2 3 4 5 6 7 8
0 1 2 3 4 5 6 7 8 9
0 1 2 3 4 5 6 7 8
0 1 2 3 4 5 6 7
0 1 2 3 4 5 6
0 1 2 3 4 5
0 1 2 3 4
0 1 2 3
0 1 2
0 1
0

Related

Linked list being overwritten instead of attached to another linked list

This is written in C.
I'm trying to take user input and use it to create/add to a linked list, which I point to with struct Node *dict; Everything is accomplished using global memory.
Creating a new linked list works fine, but when the user tries to add to the linked list, it overwrites the extant linked list.
Here's my code for adding to the list (words is an array of nodes to be appended to the list):
if (dict == NULL) { // If previous list does not exist, global dict pointer should point to node array
dict = words;
} else { // Else find end of current linked list and point it to the new list
struct Node *head = dict;
while (head->next != NULL) {
head = head->next;
}
head->next = words;
}
When I create a list with the words "apple orange peach," for example, when I print the list, I get the output "apple orange peach." But then when I add "pear" to the list, "apple orange peach" is overwritten and I only see the output "pear," instead of "apple orange peach pear."
EDIT:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
//// GUI Stuff ////
void drawDashedLine() {
for (int i = 0; i < 30; i++) {
printf("-");
}
printf("\n");
}
void drawDottedLine() {
for (int i = 0; i < 30; i++) {
printf(".");
}
printf("\n");
}
void drawArrowLine() {
for (int i = 0; i < 30; i++) {
printf(">");
}
printf("\n");
}
void drawStarLine() {
for (int i = 0; i < 30; i++) {
printf("*");
}
printf("\n");
}
struct Node {
int length;
char word[5];
struct Node * next;
};
// Pointer to global linked list dictionary
struct Node *dict;
struct Node *newDict;
void printDict() {
drawDottedLine();
struct Node * head = dict;
while (head != NULL) {
printf("%s\n", head -> word);
head = head -> next;
}
drawDottedLine();
return;
}
void alphabetizeDict() { // Bubble sort
//printf("%p --- %p\n", dict, dict->next);
struct Node * head = dict;
if (head == NULL) {
return;
}
struct Node * ptr2 = NULL;
int swapped = 1;
while (swapped) {
swapped = 0;
head = dict;
while (head -> next != ptr2) {
char * temp1 = strdup(head -> word);
char * temp2 = strdup(head -> next -> word);
strupr(temp1);
strupr(temp2);
if (strcmp(temp1, temp2) > 0) {
char temp[5];
strcpy(temp, head -> word);
strcpy(head -> word, head -> next -> word);
strcpy(head -> next -> word, temp);
swapped = 1;
}
head = head -> next;
}
ptr2 = head;
}
return;
}
void createDict() {
// To hold the string entered by the user
char str[5000];
// Holds 1000 words, each up to 5 characters long (4 plus a NULL char)
char newString[1000][5];
printf("\n");
drawArrowLine();
printf("Enter word(s): \n");
fgets(str, sizeof str, stdin);
int i, j, ctr;
j = 0;
ctr = 0; // ctr to iterate through words, j to iterate through letters
for (i = 0; i <= (strlen(str)); i++) {
if (str[i] == ' ' || str[i] == '\0') { // This is whitespace. add null character to terminate string. Start next word
newString[ctr][j] = '\0';
ctr++;
j = 0;
} else { // Else add letter to string
newString[ctr][j] = str[i];
j++;
}
}
for (int i = 0; i < ctr; i++) {
struct Node n;
n.length = strlen(newString[i]);
int c = 0;
char sub[5];
// Only use word's first four letters
while (c < strlen(newString[i]) && c < 4) {
sub[c] = newString[i][c];
c++;
}
sub[c] = '\0';
strcpy(n.word, sub);
n.next = NULL;
if (dict == NULL) {
dict = &n;
} else {
n.next = dict;
dict = &n;
}
}
// alphabetizeDict();
printf("Word(s) added succesfully\n");
drawArrowLine();
printf("\n");
return;
}
void destroyDict() {
printf("Starting new dictionary......\n");
while (dict != NULL) {
struct Node * temp = dict;
dict = dict -> next;
temp -> next = NULL;
}
}
void caseInsensSearch(char * searchTerm) {
for (int i = 0; searchTerm[i]; i++) {
searchTerm[i] = tolower(searchTerm[i]);
}
struct Node * head = dict;
int index = 0;
while (head != NULL) {
char lowercaseWord[5];
for (int i = 0; head -> word[i]; i++) {
lowercaseWord[i] = tolower(head -> word[i]);
}
if (strcmp(lowercaseWord, searchTerm) == 0) {
printf("Found %s at index %i\n", head -> word, index);
drawDashedLine();
return;
}
head = head -> next;
index++;
}
printf("Sorry, I couldn't find %s in your dictionary.\n", searchTerm);
drawDashedLine();
return;
}
void caseSensSearch(char * searchTerm) {
struct Node * head = dict;
int index = 0;
while (head != NULL) {
if (strcmp(head -> word, searchTerm) == 0) {
printf("Found %s at index %i\n", head -> word, index);
drawDashedLine();
return;
}
head = head -> next;
index++;
}
printf("Sorry, I couldn't find %s in your dictionary.\n", searchTerm);
drawDashedLine();
return;
}
void search() {
int isSens;
drawDashedLine();
printf("Enter 1 for Case sensitive\n2 for case insensitive\n");
drawDashedLine();
scanf("%d", & isSens);
while (isSens < 1 || isSens > 2) {
printf("Please enter a number between 1 and 2:\n");
scanf("%d", & isSens);
}
drawDashedLine();
printf("Enter a word to search for:\n");
char searchTerm[5];
scanf("%s", searchTerm);
searchTerm[4] = '\0';
if (isSens == 1) {
caseSensSearch(searchTerm);
} else {
caseInsensSearch(searchTerm);
}
}
int promptUser() {
drawStarLine();
printf("1) Search for a word\n2) Add word(s)\n3) Print dictionary\n4) Start new dictionary\n5) Exit\n");
drawStarLine();
printf("\nEnter a number between 1 and 5:\n");
int choice;
scanf("%1d", & choice);
while (choice < 1 || choice > 5) {
printf("Please enter a number between 1 and 5:\n");
scanf("%d", & choice);
}
return choice;
}
int main() {
for (;;) {
int choice = promptUser();
fflush(stdin);
if (choice == 1) {
search();
} else if (choice == 2) {
createDict();
} else if (choice == 3) {
printDict();
} else if (choice == 4) {
destroyDict();
} else if (choice == 5) {
return 0;
}
}
return 1;
}
I've spent some time diagnosing this problem for you. The problem statement is bizarre... An array of words could be sorted (even with library qsort()) and grow to the fill the array to the brim, but you claim this must use both a linked list and a global "object pool" that is not dynamically allocated...
Here's some code I've compiled BUT NOT TESTED...
It should be simple to follow and expand to accommodate your requirements.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct Node { // use 'typdef'. Less typing
char word[5]; // VERY SHORT WORDS guaranteed
struct Node *next;
} Node_t;
Node_t dict[ 1000 ]; // global data space
int nextNode = 0;
void printDict() { // traverse LL outputting value(s)
for( Node_t *pn = dict; pn; pn = pn->next )
puts( pn->word );
}
void addNode( char *data ) {
if( nextNode + 1 >= sizeof dict/sizeof dict[0] )
return; // Fixed size cannot grow.
Node_t *pn = &dict[ nextNode ];
strcpy( pn->word, data ); // "apple" WON'T fit
nextNode++;
//EDIT:
// This is not correct.
// See code block below for correction
if( nextNode +1 >= sizeof dict/sizeof dict[0] )
pn->next = NULL;
else
pn->next = &dict[ nextNode ];
}
void createDict() {
char str[5000]; // one lo-o-o-ong input string of short words
printf( "Enter word(s): \n" );
fgets( str, sizeof str, stdin );
// chop words on spaces (or tabs) and store to LL
for( char *cp = str; ( cp = strtok( cp, " \t" ) ) != NULL; cp = NULL )
addNode( cp );
}
void destroyDict() { // super simple!
memset( dict, 0, sizeof dict );
nextNode = 0;
// return; // Do not need those return(s) before final closing brace.
}
80% of any problem is the clear understanding of what the problem is to begin with.
EDIT: Realising the code must 'straddle' both array and LL, the above was not exactly correct. Below is the necessary fix to conform with a LL having a NULL next pointer at its 'tail' node.
void addNode( char *data ) {
if( nextNode + 1 >= sizeof dict/sizeof dict[0] )
return; // Fixed size cannot grow.
strcpy( dict[ nextNode ].word, data ); // "apple" WON'T fit
if( nextNode ) // at node 1 or greater
dict[ nextNode - 1 ].next = &dict[ nextNode ];
nextNode++;
}
try this
if (dict == NULL) { // If previous list does not exist, global dict pointer should point to node array
dict = words;
} else { // Else find end of current linked list and point it to the new list
struct Node *head = dict;
while (head->next != NULL) {
head = head->next;
}
struct Node *ptr = NULL;
ptr->length = strlen(word);
strcpy(ptr->word, sub);
ptr->next = NULL;
head->next = ptr;
}

Split a single linked list into 2 SIngly linked lists -one containing nodes with even data and other containing nodes with odd data

I tried coding the above problem but I'm getting a segmentation error.Below is the code that I've written :
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
struct oddeven
{
int data;
struct oddeven *link;
};
typedef struct oddeven m;
int main()
{
int z;
m *head=NULL,*ptr,*current;
m *x,*y,*q,*head1=NULL,*current1,*head2=NULL,*current2;
while(1)
{
int ch;
ptr=(m*)malloc(sizeof(m));
printf("Enter the data: ");
scanf("%d",&ptr->data);
ptr->link=NULL;
if(head==NULL)
{
head=ptr;
current=ptr;
}
else
{
current->link=ptr;
current=ptr;
}
printf("Do you want to continue?Y=1/N=0");
scanf("%d",&ch);
if(ch!=1)
break;
}
x=head;
while(x!=NULL)
{
z=x->data;
if(z%2==0)
{
ptr=(m*)malloc(sizeof(m));
ptr->data=z;
ptr->link=NULL;
if(head1==NULL)
{
head1=ptr;
current1=ptr;
}
else
{
current1->link=ptr;
current1=ptr;
}
}
else
{
ptr=(m*)malloc(sizeof(m));
ptr->data=z;
ptr->link=NULL;
if(head2=NULL)
{
head2=ptr;
current2=ptr;
}
else
{
current2->link=ptr;
current2=ptr;
}
}
x=x->link;
}
y=head1;
q=head2;
while (y!=NULL)
{
printf("%d\t",y->data);
y=y->link;
}
printf("\n");
while (q!=NULL)
{
printf("%d\t",q->data);
q=q->link;
}
}
I can't figure out where am I going wrong. Any help would be much appreciated.
It takes the inputs but after that it says segmentation error. Split the given single linked list into two where I can store the odd vales and even values separately .I tried different methods but couldn't get it to work.
#VladfromMoscow mentions one reason why your program faults, but it is too complicated anyway. Here is a simpler version. With a singly linked list, you don't need a separate operation for the first element, when head == NULL. You don't need any new nodes when splitting, just relink.
#include <stdio.h>
#include <stdlib.h>
struct oddeven {
int data;
struct oddeven *link;
};
typedef struct oddeven m;
int main(void) {
int num;
m *head = NULL, *ptr;
// read the list and end it with any letter or non-digit
while(scanf("%d", &num) == 1) {
ptr = malloc(sizeof *ptr);
if(ptr == NULL) {
exit(1);
}
ptr->data = num;
ptr->link = head;
head = ptr;
}
// split the list
m *x, *odd = NULL, *even = NULL, *next;
x = head;
while(x != NULL) {
next = x->link; // remember what the link was
if(x->data % 2 == 0) {
x->link = even;
even = x;
}
else {
x->link = odd;
odd = x;
}
x = next;
}
// output the odds
m *y = odd;
while (y != NULL) {
printf("%d\t", y->data);
y = y->link;
}
printf("\n");
// output the evens
m *q = even;
while (q != NULL) {
printf("%d\t", q->data);
q = q->link;
}
printf("\n");
}
Program session:
1 5 8 3 44 9 0 1 4 3 6 77 3 42 q
1 5 3 9 1 3 77 3
8 44 0 4 6 42

C Thread bad access error when input string (link list)

I have been getting Thread 1 : EXC_BAD_ACCESS error when trying to push a string element into the stack. I've changed the char* name to char name[21] but the assignment char[21] is not assignable to curr->name. Also I've tried fgets but the error still there. Anyone know where the error?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct parts
{
char* name;
char* type;
int quantity;
int price;
int num;
struct parts * next;
}*head,*tail,*curr,komponen;
void menu();
void show_Parts();
void push(char* nm, char* tip, int jml, int harga, int nom);
void del();
int main() {
menu();
del();
getchar();
return 0;
}
void push(char* nm, char* tip, int jml, int harga, int nom)
{
// 1.
curr = (struct parts *)malloc(sizeof(struct parts));
// 2.
if (curr == NULL) {
exit(0);
}
head = NULL;
head = curr->next;
curr->name = nm;
curr->type = tip;
curr->quantity = jml;
curr->price = harga;
curr->num = nom;
curr = head;
//
printf("Input name of the new item [3..20]: ");
scanf("%s",nm);
if (strlen(nm) < 3 || strlen(nm) > 20) {
printf("Length of name must between 3 and 20");
exit(0);
}
printf("Input type of the new item [processor/graphic card/memory]: ");
scanf("%s",tip);
if (tip != "processor" || tip != "graphic card" || tip != "memory") {
printf("Input type of existing item. Error");
exit(0);
}
printf("Input quantity of the new item [1..20]: ");
scanf("%d",&jml);
if (jml < 1 || jml > 20) {
printf("Quantity between 1 and 20\n");
exit(0);
}
printf("Input price of new item [$1..$1000]: ");
scanf("%d",&harga);
if (harga < 1 || harga > 1000) {
printf("Price between 1 and 1000\n");
exit(0);
}
nom++;
printf("--- Add New Item Success ---\n");
tail->next = NULL;
}
void del()
{
if (curr == NULL) {
exit(0);
}
curr = head;
head = head->next;
free(curr);
}
void menu()
{
int choic;
do {
printf("BLUE COMPUTER ADMINISTRATOR\n");
printf("++++++++++++++++++++++++++++\n");
printf("1. Item list\n");
printf("2. Add <PUSH> New item\n");
printf("3. Exit\n");
printf(">> Input your choice : ");
switch (choic) {
case 1:
show_Parts();
break;
case 2:
push(komponen.name,komponen.type,komponen.price, komponen.quantity, komponen.num);
break;
case 3:
del();
exit(0);
break;
}
scanf("%d",&choic);
} while (choic != 3);
}
void show_Parts()
{
if (curr == NULL) {
printf("No item in list\n");
exit(0);
}
printf(" ---- ITEM LIST ---- \n\n");
printf("-----+------------------+--------+-----------+--------\n");
printf("|No. | Name | Type | Quantity | Price|\n");
do {
printf("|%d |%s |%s |%d |%d \n",curr->num, curr->name, curr->type, curr->quantity, curr->price);
curr = curr->next;
}while (curr != NULL);
}
Thanks.

Pop function in from my linked list of FIFO in C is not working

In a few days, I'm having a very important exam about C. My awesome teacher is helping me a little bit and gave me this test, among other things. Here I have to make the function "pop." I gave it a try almost the whole weekend, but it still isn't working, and it's getting me frustrated. Maybe you guys could help me. I want the pop to be FIFO.
#include <stdio.h>
typedef struct test NODE;
typedef NODE *NV;
struct test
{
int data;
NV next;
};
int empty(NV);
int geeftop(NV);
void pop(NV, NV *, NV *);
void push(NV *, NV *, int);
int main(void)
{
int k, number;
int controle;
NV start;
NV staart;
staart = NULL;
start = NULL;
do
{
system("CLS");
printf("\nKeuzemenu:\n");
printf("[1] = ADD.\n");
printf("[2] = DELETE.\n");
printf("[3] = IS IT EMPTY?.\n");
printf("[4] = Stop.\n\n");
printf("type your number: ");
do
{
scanf("%d", &k);
} while (k <= 0 || k >= 5);
switch (k)
{
case 1: printf("give a number: ");
scanf("%d", &number);
push(&start, &staart, number);
break;
case 2: if (!empty(start))
{
pop(start, &start ,&staart);
printf("\ntop is deleted.\n\n");
}
else
printf("\nerror.\n\n");
system("PAUSE");
break;
case 3: controle = empty(start);
if (controle == 1)
printf("\nits emtpy.\n\n");
else
printf("\nniet empty.\n\n");
system("PAUSE");
break;
default: break;
}
} while (k != 4);
system("PAUSE");
return 0;
}
int empty(NV phuidige)
{
return (phuidige == NULL);
}
void pop(NV phuidige2, NV *phuidige, NV *pstaart)
{
if ((phuidige2) -> next == NULL)
{
NV weg;
NV weg2;
weg = *pstaart;
weg2 = *phuidige;
pstaart = NULL;
phuidige2 = NULL;
free (pstaart);
free (phuidige2);
}
else
{
while ((phuidige2) -> next -> next != (NULL))
{
phuidige2 = phuidige2 -> next;
}
}
{
phuidige2 -> next = NULL;
NV weg;
weg = *pstaart;
*pstaart = NULL;
free (weg);
}
}
void push(NV *phuidige, NV *pstaart, int x)
/* pre er is ruimte op de stack;
post stack(post) = stack(pre) U {x}; */
{
NV hulp;
hulp = malloc(sizeof(NODE));
hulp -> data = x;
hulp -> next = *phuidige;
*phuidige = hulp;
if (*pstaart == NULL)
{
*pstaart = hulp;
}
else
{
}
}
You should really check the return value from scanf, the value of k is uninitialised. Basically pop should just return your head pointer, and advance the head pointer to the next element - checking for null as you go.

C. Linked lists. Inserting an element before another

Right now I have a program (shown below) that inserts an element (E) after (F). For example if we input n = 4 and then insert 4 elements 2 3 3 4, followed by our 'F' value which is 3 and E value which is 6, the program will edit the list inserting E (6) after F (3), resulting in a list edition from 2 3 3 4 into 2 3 6 3 4
I am looking for a way to insert a value 'E' BEFORE an F, not after. Could anyone explain what changes may be required to this code to achieve the same?
#include <stdio.h>
#include <stdlib.h>
struct sarasas { int duomuo; struct sarasas *next, *prev; };
typedef struct sarasas Sarasas;
typedef Sarasas *SarasasPtr;
int main()
{
int d,i,n,j,e,f;
SarasasPtr Sar,x,temp,prev=NULL;
SarasasPtr head= NULL;
printf("Insert 'n' \n");
scanf("%d",&n);
for (i=0; i<n; i++) {
printf("Insert an element: \n");
scanf("%d",&d);
x=(SarasasPtr) malloc(sizeof( Sarasas ));
x->duomuo = d;
x->next = NULL;
if(head == NULL) {
head = x;
} else {
temp = head;
while(temp!=NULL) {
prev = temp;
temp = temp->next;
}
prev->next = x;
}
}
printf("Insert an element after which one you want another element to be inserted\n");
scanf("%d",&e);
printf("Insert element which you want to insert\n");
scanf("%d",&f);
temp = head;
int pakeista = 0;
while(temp!=NULL) {
//printf("%d",temp->duomuo);
if (temp->duomuo == e) {
if (changed == 0) {
x=(SarasasPtr) malloc(sizeof( Sarasas ));
x->duomuo=f;
x->next=temp->next;
temp->next=x;
n++;
changed = 1;
}
}
temp=temp->next;
}
Sar = head;
for (i=0; i<n; i++) {
printf("Sk Nr. %i: %d\n",i+1,Sar->duomuo);
Sar = Sar->next;
}
}
You simply need to check temp->next->duomuo instead of temp->duomuo
while(temp->next!=NULL) {
if (temp->next->duomuo == e) {
if (changed == 0) {
x=(SarasasPtr) malloc(sizeof( Sarasas ));
x->duomuo=f;
x->next=temp->next;
temp->next=x;
n++;
changed = 1;
}
}
temp=temp->next;
}
I would also suggest that instead of this changed thing that you are doing, just break from the loop after you replace. This way your loop won't run more times than it needs to.
while(temp->next!=NULL) {
if (temp->next->duomuo == e) {
x=(SarasasPtr) malloc(sizeof( Sarasas ));
x->duomuo=f;
x->next=temp->next;
temp->next=x;
n++;
break;
}
temp=temp->next;
}

Resources