Linked List Program Error - c

Wrote this program in C for linked Lists. I am getting an error in insert when trying to insert at the end of the linked list as a segmentation fault. All other cases are working such as inserting initially,inserting in between 2 elements,etc. Spent a lot of time pondering but couldnt figure out?
#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
void insert();
void display();
void search();
void delete();
struct node{
int val;
struct node *next;
}*head;
int num,count=0;
void main()
{
char dec = 'E';
printf("Welcome to the Linked List C Program!\n");
head = NULL;
while(1){
printf("Make a Choice:\n");
printf("I.Insert\nD.Delete\nS.Search\nd.Display\nE.Exit\n");
scanf(" %c",&dec);
switch(dec){
case 'I':
insert();
break;
case 'D':
delete();
break;
case 'S':
search();
break;
case 'd':
display();
break;
case 'E':
exit(0);
break;
default:
printf("Wrong input Try Again!\n");
}
}
}
void insert(){
printf("Enter the number to insert:");
scanf("%d",&num);
struct node *temp;
struct node *newnode;
struct node *prev;
int c =0;
//temp = (struct node *)malloc(sizeof(struct node));
newnode = (struct node *)malloc(sizeof(struct node));
//prev = (struct node *)malloc(sizeof(struct node));
newnode->val = num;
if(head==NULL)
{
head = newnode;
head->next = NULL;
}
else
{
temp = head;
//searching whether linked list is in start or end
while(temp->val<num && temp !=NULL)
{
printf("Index:%d Value:%d Address:%p",c,temp->val,temp);
prev = temp;
temp = temp->next;
c++;
printf("TEST\n");
}
if(c==0)
{
head = newnode;
head->next = temp;
}
else
{
prev->next=newnode;
newnode->next=temp;
}
}
}
void display()
{
struct node *temp;
temp = (struct node *)malloc(sizeof(struct node));
temp = head;
while(temp != NULL)
{
printf("%d",temp->val);
temp = temp->next;
}
if(temp == NULL)
{
printf("Not present!");
}
}
void search()
{
printf("Enter the number tosearch for:\n");
scanf("%d",&num);
struct node *temp;
temp=head;
int c=0;
while(temp!=NULL)
{
if(temp->val==num)
{
printf("Present at position %d",c);
c++;
}
else if(temp == NULL)
{
printf("Not present!");
}
else
c++;
temp =temp->next;
}
}
void delete()
{
struct node *temp;
struct node *prev;
temp = head;
printf("Enter the value to delete:\n");
scanf("%d",&num);
int c=0;
while(temp!=NULL)
{
if(temp->val==num)
{
printf("Present at position %d",c);
printf("Deleting this element");
prev->next=temp->next;
free(temp);
c++;
}
else
c++;
prev = temp;
temp =temp->next;
}
if(temp == NULL)
{
printf("Not present!");
}
}

In your while loop, you're checking one of temp's members before checking that temp is not NULL:
while(temp->val<num && temp !=NULL)
reverse that:
while ((temp != NULL) && (temp->val < num))

Related

Creating a C string array, when reading from file

im doing a project, where i need to manage a queue of sorts, specifically cars in a car wash. I've found some code online, that allows you to add to queue and manage it, with integer inputs. Is there a way for me to re-write this code, so that it accepts inputs as c strings instead of integers?
#include <stdio.h>
#include <stdlib.h>
struct node
{
int data;
struct node *next;
};
struct node *front = NULL;
struct node *rear = NULL;
void display();
void enqueue(int);
void dequeue();
int main()
{
int n, ch;
do
{
printf("\n\nQueue Menu\n1. Add \n2. Remove\n3. Display\n0. Exit");
printf("\nEnter Choice 0-3? : ");
scanf("%d", &ch);
switch (ch)
{
case 1:
printf("\nEnter number ");
scanf("%d", &n);
enqueue(n);
break;
case 2:
dequeue();
break;
case 3:
display();
break;
}
}while (ch != 0);
}
void enqueue(int item)
{
struct node *nptr = malloc(sizeof(struct node));
nptr->data = item;
nptr->next = NULL;
if (rear == NULL)
{
front = nptr;
rear = nptr;
}
else
{
rear->next = nptr;
rear = rear->next;
}
}
void display()
{
struct node *temp;
temp = front;
printf("\n");
while (temp != NULL)
{
printf("%d\t", temp->data);
temp = temp->next;
}
}
void dequeue()
{
if (front == NULL)
{
printf("\n\nqueue is empty \n");
}
else
{
struct node *temp;
temp = front;
front = front->next;
printf("\n\n%d deleted", temp->data);
free(temp);
}
}
Where the desired input would be one of these strings;
AV96888 VW alm
KD65656 Audi luksus
AX21878 Ford alm
CN32323 VW alm
NB21214 Ford luksus
UM21878 Ford alm
AV54361 Tesla luksus
Yes, the data is stored in the node:
struct node
{
int data;
struct node *next;
};
So you just need to change the int data; to a string.
Are there a reason you are doing this in C and not c++ ? There, string management is easier.
Here is the answer, you just convert the data to char * and use strdup to store the pointer
#include "stdlib.h"
#include "stdio.h"
#include "string.h"
struct node
{
char *data;
struct node *next;
};
struct node *front = NULL;
struct node *rear = NULL;
void enqueue(char *item)
{
struct node *nptr = malloc(sizeof(struct node));
nptr->data = strdup(item);
nptr->next = NULL;
if (rear == NULL)
{
front = nptr;
rear = nptr;
}
else
{
rear->next = nptr;
rear = rear->next;
}
}
void display()
{
struct node *temp;
temp = front;
printf("\n");
while (temp != NULL)
{
printf("%s\t", temp->data);
temp = temp->next;
}
}
void dequeue()
{
if (front == NULL)
{
printf("\n\nqueue is empty \n");
}
else
{
struct node *temp;
temp = front;
front = front->next;
printf("\n\n%d deleted", temp->data);
free(temp->data);
free(temp);
}
}
int main()
{
int ch;
char n[256];
do {
printf("\n\nQueue Menu\n1. Add \n2. Remove\n3. Display\n0. Exit");
printf("\nEnter Choice 0-3? : ");
scanf("%d", &ch);
switch (ch)
{
case 1:
printf("\nEnter a name: ");
scanf("%s", n);
enqueue(n);
break;
case 2:
dequeue();
break;
case 3:
display();
break;
}
}while (ch != 0);
}

linked list node bug infinity loop of node and insert between node

when i created the third node it made the infinity loop of that node. what should i do?
and please insert the code in case 'b' for insert node behind some node.
part1-----------------------------------------------------------------------------------------------------------------------------
#include<stdio.h>
#include<stdlib.h>
#include<stdbool.h>
char p,j ;
int v;
struct node{
int val;
struct node *next;
};
struct node *head=NULL;
struct node *curr=NULL;
struct node *temp=NULL;
struct node *prev=NULL;
struct node *tail=NULL;
struct node *after=NULL;
part2-----------------------------------------------------------------------------------------------------------------------------
struct node *creatFirstNode(int val){
printf("\ncreating list with headnode as [%d]\n",val);
struct node *ptr=(struct node *)malloc(sizeof(struct node));
if(ptr==NULL){
printf("\nCreated Failed \n");
return NULL;
}
ptr->val=val;
ptr->next=NULL;
head=ptr;
curr=ptr;
return ptr;
}
part3-----------------------------------------------------------------------------------------------------------------------------
main(){
int n,i;
struct node *A=(struct node *)malloc(sizeof(struct node));
struct node *B=(struct node *)malloc(sizeof(struct node));
struct node *C=(struct node *)malloc(sizeof(struct node));
struct node *new=(struct node *)malloc(sizeof(struct node));
struct node *addEnd=(struct node *)malloc(sizeof(struct node));
struct node *addAmong=(struct node *)malloc(sizeof(struct node));
printf("\n-------- Welcome to Linked List Program -----------\n\n");
do{
printf("\nAdd to 'h'ead or 't'ail or 'b'ehind value:");
scanf("%c",&p);
fflush(stdin);
part4-----------------------------------------------------------------------------------------------------------------------------
switch(p)
{
case 'h':
printf("Enter value node:");
scanf("%d",&v);
fflush(stdin);
if(head == NULL)
{
creatFirstNode(v);
fflush(stdin);
}
else
{
curr=head;
new->val=v;
new->next=NULL;
curr=new;
curr->next=head;
curr=curr->next;
("\ncreating list with headnode as [%d]\n",v);
head=new;
fflush(stdin);
}
//void printList();
curr=head;
printf("\n----Value in Liked list----\n");
while(curr!=NULL){
printf("[%d], ",curr->val);
curr=curr->next; //change current node
}
break;
part5-----------------------------------------------------------------------------------------------------------------------------
case 't':
printf("Enter value node tail:");
scanf("%d",&v);
curr=head;
while(curr!=NULL){ //Seek for last node
tail=curr;
curr=curr->next; // shift to next node
}
addEnd->val=v;
addEnd->next=NULL;
tail->next=addEnd;
tail=new;
fflush(stdin);
//void printList();.
curr=head;
printf("\n----Value in Liked list----\n");
while(curr!=NULL){
printf("[%d], ",curr->val);
curr=curr->next; //change current node
}
break;
part6-----------------------------------------------------------------------------------------------------------------------------
case 'b':
printf("Enter value node behind:");
scanf("%d",&v);
fflush(stdin);
printf("Adding value [%d] in new node:",&v);
printf("Add new node behind the value:");
void printList();
break;
default:
printf("\n Invalid Input ");
getch();
}
}while(p != 'h' || p != 't' || p != 'b' );
getch();
return 0;
}
example
#include <stdio.h>
#include <stdlib.h>
typedef struct node {
int val;
struct node *next;
} Node;
Node *head, *tail;
Node *new_node(int val){
struct node *ptr = malloc(sizeof(*ptr));
if(ptr==NULL){
perror("malloc:");
printf("\nFailed to create a new node.\n");
return NULL;
}
ptr->val = val;
ptr->next = NULL;
return ptr;
}
Node *creatFirstNode(int val){
return head = tail = new_node(val);
}
void printList(void){
Node *np = head;
printf("\n----Value in Liked list----\n");
while(np){
printf("[%d], ", np->val);
np = np->next;
}
printf("NULL\n");
}
void freeList(void){
while(head){
Node *np = head->next;
free(head);
head = np;
}
tail = NULL;
}
int main(void){
char cmd =' ';
printf("\n-------- Welcome to Linked List Program -----------\n\n");
do {
int v = 0;
printf("\nAdd to 'h'ead or 't'ail or 'b'ehind value or 'p'rint or 'q'uit:");
scanf(" %c", &cmd);
switch(cmd){
case 'h':
printf("Enter value node head:");
scanf("%d", &v);
if(head == NULL){
creatFirstNode(v);
} else {
Node *np = new_node(v);
np->next = head;
head = np;
}
break;
case 't':
printf("Enter value node tail:");
scanf("%d", &v);
if(head == NULL){
creatFirstNode(v);
} else {
tail = tail->next = new_node(v);
}
break;
case 'b':
printf("Enter value node behind:");
scanf("%d", &v);
printf("\nUnimplemented yet.\n");
break;
case 'p':
printList();
break;
case 'q':
freeList();
printf("\nBye!\n");
break;
default:
printf("\n Invalid Input ");
}
}while(cmd != 'q' );
return 0;
}

C linked list node not add

I want to add newnode behind headnode or others node but node not add whay Should i do?
#include <stdio.h>
#include <stdlib.h>
typedef struct node {
int val;
struct node *next;
} Node;
Node *head, *tail, *behind, *prev,*twonext;
Node *new_node(int val){
struct node *ptr = malloc(sizeof(*ptr));
if(ptr==NULL){
perror("malloc:");
printf("\nFailed to create a new node.\n");
return NULL;
}
ptr->val = val;
ptr->next = NULL;
return ptr;
}
Node *creatFirstNode(int val){
return head = tail = new_node(val);
}
void printList(void){
Node *np = head;
printf("\n----Value in Liked list----\n");
while(np){
printf("[%d], ", np->val);
np = np->next;
}
// printf("NULL\n");
}
void freeList(void){
while(head){
Node *np = head->next;
free(head);
head = np;
}
tail = NULL;
}
int main(void){
char cmd =' ';
int k;
printf("\n-------- Welcome to Linked List Program -----------\n\n");
do {
int v = 0;
int s = 0;
printf("\nAdd to 'h'ead or 't'ail or 'b'ehind value or 'p'rint or 'q'uit:");
scanf(" %c", &cmd);
fflush(stdin);
switch(cmd){
add headnode--------------------------------------------------------------------
case 'h':
printf("Enter value node head:");
scanf("%d", &v);
if(head == NULL){
creatFirstNode(v);
} else {
Node *np = new_node(v);
np->next = head;
head = np;
}
fflush(stdin);
printList();
break;
add tail node --------------------------------------------------------------------
case 't':
printf("Enter value node tail:");
scanf("%d", &v);
if(head == NULL){
creatFirstNode(v);
} else {
tail = tail->next = new_node(v);
}
fflush(stdin);
printList();
break;
add behind node I have problem here What Should i do?? -----------------------------------------------
case 'b':
printf("Enter node value:");
scanf("%d",&v);
Node *np = new_node(v);
printf("Adding value [%d] in new node:",v);
// behind = behind->next = new_node(v);
if(head == NULL)
{
printf("No node to insert behind:");
}
else
{
printf("\nAdd new node behind the value:");
scanf("%d", &s);
np = head;
while(np->val != s);
{
prev=np;
np =np->next;
}
twonext=np->next;
np->next=NULL;
np->next=twonext;
}
fflush(stdin);
printList();
break;
/*case 'p':
printList();
break;
*/
case 'q':
freeList();
printf("\nBye!\n");
getch();
break;
default:
printf("\n Invalid Input ");
}
}while(cmd != 'q' );
return 0;
}
Basically if you want to put a new node between others you've to link the prev->next with the new one and the new->next with the next node. That's all, here is a code example.
case 'b':
printf("Enter node value:");
scanf("%d",&v);
Node *np = new_node(v);
printf("Adding value [%d] in new node:",v);
// behind = behind->next = new_node(v);
if(head == NULL)
{
printf("No node to insert behind:");
}
else
{
printf("\nAdd new node behind the value:");
scanf("%d", &s);
Node *tmp = head; /*You need a tmp variable to go through the list*/
while(tmp->val != s && tmp != NULL);
{
prev=tmp; /*Save the prev node*/
tmp =tmp->next; /*Go through*/
}
if(tmp != NULL){
prev->next = np; /*Link the prev with the new*/
np->next = tmp; /*Link the new one with the subsequent*/
}
}
fflush(stdin);
printList();
break;

Delete string from linked list - C [duplicate]

This question already has an answer here:
Delete element of linked list by a certain criterion
(1 answer)
Closed 7 years ago.
So the problem I'm running into is deleting a user-inputted string from a linked list full of strings.
I'm still having a few issues in understanding just precisely how linked lists work, so any explanation as to what I am doing wrong would be greatly appreciated!
Also, every other function seems to be working just fine, just having issues with the deleteItem function!
Edit - The problem I'm getting when I run the deleteItem function is just my terminal window crashing after getting hung up for a bit.
Here's my code:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
struct node
{
char name[50];
struct node *next;
}*head;
void display();
void insert();
void count();
void deleteItem();
int main(){
int choice = 1;
char name[50];
struct node *first;
head = NULL;
while(1){
printf("Menu Options\n");
printf("----------------\n");
printf("Please enter the number of the operation you'd like to do: \n");
printf("----------------\n");
printf("1. Insert\n");
printf("2. Display\n");
printf("3. Count\n");
printf("4. Delete\n");
printf("5. Exit\n");
printf("----------------\n");
scanf("%d",&choice);
switch(choice)
{
case 1:
insert();
break;
case 2:
display();
break;
case 3:
count();
break;
case 4:
if(head=NULL)
printf("The list is blank");
else
deleteItem();
break;
case 5:
return 0;
default:
printf("invalid option");
}
}
system("pause");
return 0;
}
void insert(){
char nameToInsert[50];
struct node *temp;
temp = head;
if(head == NULL){
head = (struct node *)malloc(sizeof(struct node));
printf("What's the name you wish to insert?\n");
scanf("%s", &nameToInsert);
strcpy(head->name, nameToInsert);
head->next = NULL;
}
else{
while(temp->next !=NULL){
temp = temp->next;
}
temp->next = malloc(sizeof(struct node));
temp = temp->next;
printf("What's the name you wish to insert?\n");
scanf("%s", &nameToInsert);
strcpy(temp->name, nameToInsert);
temp->next = NULL;
}
}
void display(){
struct node *temp;
temp = (struct node *)malloc(sizeof(struct node));
temp = head;
if(temp == NULL)
printf("The list is empty\n");
else{
printf("%s\n", temp->name);
while(temp->next != NULL){
temp = temp->next;
printf("%s\n", temp->name);
}
}
}
void count(){
struct node *temp;
int c =0;
temp = head;
while(temp!=NULL){
temp=temp->next;
c++;
}
printf("\n%d", c);
}
void deleteItem(){
char nameToDelete[50];
struct node *temp, *previous;
temp = head;
printf("What is the name you wish to delete?\n");
scanf("%s", nameToDelete);
while(temp->next != NULL){
temp = temp->next;
if(strcmp(nameToDelete, temp->name)==0){
previous = temp->next;
free(temp);
printf("%s was deleted successfully\n", nameToDelete);
}
}
}
I see the following issues:
You are not dealing with the case where the item to delete is at the head of the list.
The linked list is not restored to a good state after you free the node that contains the item.
You continue to iterate over the list even after you free the node that contains the item.
Here's a version that should work.
void deleteItem(){
char nameToDelete[50];
struct node *temp, *previous;
temp = head;
printf("What is the name you wish to delete?\n");
scanf("%s", nameToDelete);
// First, locate the node that contains the item.
for ( ; temp->next != NULL; temp = temp->next )
{
if(strcmp(nameToDelete, temp->name)==0)
{
break;
}
prev = temp;
}
// Now take care of deleting it.
if ( temp != NULL )
{
if ( temp == head )
{
head = temp->next;
}
else
{
prev->next = temp->next;
}
free(temp);
printf("%s was deleted successfully\n", nameToDelete);
}
}

How can I create this linked list with stack in C?

I can create the linked list. But I could not managed to create the stack with it. (Stack cannot be more than 5, and it can be empty as shown in the link). How can I do it? (C language but C++ functions like new int are allowed)
The structure could be something like:
struct linkedStack {
int elements[5];
int top;
struct linkedStack *next;
};
Then manage the stack with top (equals to zero at the beginning)...
Post your code please so we can understand what you are trying to make.
This example can help you
#include<stdio.h>
#include<conio.h>
#include<process.h>
#include<stdlib.h>
#include<alloc.h>
void Push(int, node **);
void Display(node **);
int Pop(node **);
int Sempty(node *);
typedef struct stack {
int data;
struct stack *next;
} node;
void main() {
node *top;
int data, item, choice;
char ans, ch;
clrscr();
top = NULL;
printf("\nStack Using Linked List : nn");
do {
printf("\n\n The main menu");
printf("\n1.Push \n2.Pop \n3.Display \n4.Exit");
printf("\n Enter Your Choice");
scanf("%d", &choice);
switch (choice) {
case 1:
printf("\nEnter the data");
scanf("%d", &data);
Push(data, &top);
break;
case 2:
if (Sempty(top))
printf("\nStack underflow!");
else {
item = Pop(&top);
printf("\nThe popped node is%d", item);
}
break;
case 3:
Display(&top);
break;
case 4:
printf("\nDo You want To Quit?(y/n)");
ch = getche();
if (ch == 'y')
exit(0);
else
break;
}
printf("\nDo you want to continue?");
ans = getche();
getch();
clrscr();
} while (ans == 'Y' || ans == 'y');
getch();
}
void Push(int Item, node **top) {
node *New;
node * get_node(int);
New = get_node(Item);
New->next = *top;
*top = New;
}
node * get_node(int item) {
node * temp;
temp = (node *) malloc(sizeof(node));
if (temp == NULL)
printf("\nMemory Cannot be allocated");
temp->data = item;
temp->next = NULL;
return (temp);
}
int Sempty(node *temp) {
if (temp == NULL)
return 1;
else
return 0;
}
int Pop(node **top) {
int item;
node *temp;
item = (*top)->data;
temp = *top;
*top = (*top)->next;
free(temp);
return (item);
}
void Display(node **head) {
node *temp;
temp = *head;
if (Sempty(temp))
printf("\nThe stack is empty!");
else {
while (temp != NULL) {
printf("%d\n", temp->data);
temp = temp->next;
}
}
getch();
}

Resources