I am a first time poster so, I don't exactly know the norms, forgive me if my formatting is bad.
I am new to C programming and recently picked up on linked lists, the below code was my crappy attempt at making one.. I was wondering if anyone would be kind enough to go through my code and explain why I am facing issues. Thanks in advance! I will try my best to answer any questions!
To explain some of my functions,
- createlinklist: just initializes struct linklist and adds an int value
- addlinkfirst: adds a node at the end
- removelinklast: removes a node from the end
- dispalylinklist: prints the contents of the linklist
Code:
#include<stdio.h>
struct linklist {
int data;
struct linklist* link;
};
void createlinklist (struct linklist* newlist, int data){
newlist->data = data;
newlist->link = NULL;
}
void addlinkfirst (struct linklist* list, int data){
while(list->link != NULL)
list = list->link;
struct linklist *newlist = malloc(sizeof(struct linklist));
newlist->link = NULL;
list->link = &newlist;
newlist->data = data;
}
void removelinklast (struct linklist* list){
struct linklist* temp;
while(list != NULL){
temp = &list;
list = list-> link;
}
temp->data = NULL;
temp->link = NULL;
}
void displaylinklist (struct linklist* list) {
printf("\n");
while(list != NULL){
printf(" %d-",list->data);
list = list->link;
}
printf("\n");
}
int main () {
int x = 1, data, x1;
struct linklist test;
while(x!=0){
printf("Press 4 to create, Press 1 insert, Press 2 delete, Press 3 Display, Press 0 to Exit \n");
scanf("%d",&x);
//i assume you will be choosing 4 first then the other options
switch(x){
case 4: printf("\nEnter data for the first element:"); scanf("%d",&data); createlinklist(&test,data); break;
case 1: printf("\nEnter data:"); scanf("%d",&x1); addlinkfirst(&test,x1); break;
case 2: printf("\nDeleted"); removelinklast(&test); break;
case 3: displaylinklist(&test); break;
case 0: break;
default: printf("Invalid Input Try again\n");
}
}
printf("\nThank you for using my linklist program;");
return 0;
}