I'm having trouble adding an element to the beginning in my linked list.
#include <conio.h>
#include "list.h"
int main () {
nodePtr L;
L = createList();
L = makeNode(20);
display(L);
addFront(L,25);
display(L);
return 0;
}
and This is my library, it just prints NODE INSERTED instead of being really inserted at the front.
#include <stdlib.h>
#include <stdio.h>
#ifndef list_h
#define list_h
typedef int itemType;
typedef struct node *nodePtr;
struct node{
itemType item;
nodePtr next;
};
nodePtr createList(); //init list
nodePtr makeNode(itemType x); //allocate node
void display(nodePtr L); //print output
void addFront(nodePtr L, itemType x); //add as first element
nodePtr createList() {
nodePtr L;
L= (nodePtr) malloc(sizeof(struct node));
L->next= NULL;
return L;
}
nodePtr makeNode(itemType x) {
nodePtr temp = (nodePtr) malloc(sizeof(struct node));
temp->item=x;
temp->next=NULL;
return temp;
}
void display(nodePtr L) {
nodePtr temp;
temp = L;
while (temp!=NULL) {
printf("%d", temp->item);
temp = temp->next;
}
}
void addFront(nodePtr L, itemType x) {
nodePtr newNode = (nodePtr) malloc(sizeof(struct node));
if(newNode == NULL) {
printf("Unable to allocate memory.");
}
else {
newNode->item = x;
newNode->next = L;
L=newNode;
printf("NODE INSERTED");
}
}
#endif
I don't really understand what is wrong, I'm trying to follow the format which initializes typedef nodePtr and itemType from my teacher but I can actually understand the concept of adding the element at the front without following my teacher's format, I just need to understand how her format works as an alternative.