difficulty in creating linked list - c

In this programm, when I create a list then it creates list successfully. But when I try to print it the program is just displaying last two values of node. I debug many times and found (*temp)->next changes the start1 and start2 pointer. I'm unable to solve how temp pointer changes value in start1 and start2.
Compiler didn't produce any error or warning.
#include <stdio.h>
struct node {
int info;
struct node *next;
} *start1 = NULL, *start2 = NULL;
void create_node(struct node **s1);
void display(struct node **s);
void create_node(struct node **s1)
{
struct node *ptr = NULL, **temp = s1;
ptr = (struct node *)malloc(sizeof(struct node));
if (*s1 == NULL)
{
*s1 = ptr;
} else
{
while ((*temp)->next != NULL)
(*temp) = (*temp)->next;
(*temp)->next = ptr;
}
ptr->next = NULL;
printf("enter the value\n");
scanf("%d", &(ptr->info));
}
void display(struct node **s)
{
struct node **temp = s;
while ((*temp) != NULL)
{
printf("%d\t", (*temp)->info);
(*temp) = (*temp)->next;
}
}
void main()
{
int choice = 0;
while (1){
clrscr();
printf("enter your choice\n");
printf("enter 1 to create_node1\nenter 2 to create node 2 \nenter 3 to display node 1\nenter 4 to display node2\nenter 5 to exit\n");
printf("\n");
scanf("%d", &choice);
switch (choice)
{
case 1:
create_node(&start1);//correct//
break;
case 2:
create_node(&start2);
break;
case 3:
display(&start1);
getch();
break;
case 4:
display(&start2);
getch();
break;
case 5:
exit(1);
break;
default:
printf("invalid");
}
}
}

Use this
while ((*temp)->next != NULL) (*temp) = (*temp)->next;.
This will solve the problem.
Otherwise, the index out of memory is accessed and program crash.

Related

Segmentation Fault while working with linked list in C

I am a newbie to c. The question is to implement a Reastuarent Management Software using Linkedlist. A user should be able to enter their order and view their order. A user who pays additional amount for fast delivery should be appeared on top of the order list.
My code, while executing shows no erros but while running it shows segmentation fault when I try to enter the second entry or try to display the list.
#include<stdio.h>
#include<malloc.h>
#include<stdlib.h>
struct items{
char *item_name;
float cost;
};
struct items array[] = {
{"Pizza",49.9},{"Apples",22.0},{"Oranges",10.5},{"Grapes",3.5},{"Parotta",4.5}
};
struct bill_item{
int bill_no;
char* customer_name;
int order_item_no;
int quantity;
float total;
struct bill_item *next;
};
struct bill_item* head;
int count=0;
void insert_at_start(struct bill_item* node);
void insert_at_end(struct bill_item* node);
void book();
void display_list();
void main(){
int choice;
head = (struct bill_item*)malloc(sizeof(struct bill_item));
head->next = NULL;
while(choice!=3){
printf("\n----------------------------------------------");
printf("\n1.Book\t2.Check Orders\t3.Exit\nEnter option: ");
scanf("%d",&choice);
printf("\n------choice %d",choice);
switch(choice){
case 1: book();
printf("\nItem Purchased!!");
break;
case 2: display_list();
break;
case 3: break;
default: printf("\nEnter the correct option");
break;
}
}
}
void insert_at_start(struct bill_item* node){
if(head->next == NULL){
head->next = node;
}
else{
node->next = head;
head->next = node;
}
}
void insert_at_end(struct bill_item* node){
struct bill_item* ptr = head;
if(head->next==NULL)
head->next = node;
else{
while(ptr->next!=NULL){
ptr = ptr->next;
}
ptr->next = node;
}
}
void book(){
char c;
struct bill_item* node = (struct bill_item*)malloc(sizeof(struct bill_item));
int i=0,choice;
printf("\nMenu");
printf("\n-----------------");
for (i=0;i<5;i++){
printf("\n%d %s : %.2f",i+1,array[i].item_name,array[i].cost);
}
printf("\nEnter choice: ");
scanf("%d",&choice);
printf("\nEnter quantity: ");
scanf("%d",&node->quantity);
node->next = NULL;
count++;
node->bill_no = count;
node->total = array[choice-1].cost*node->quantity;
fflush(stdin);
printf("\nEnter customer name: ");
fgets(node->customer_name,30,stdin);
fflush(stdin);
printf("\nPurchase amount: %.2f \nNeed fast delivery(Extra 100rs will be charges)(y/n)?",node->total);
c = getc(stdin);
fflush(stdin);
if(c=='Y' || c=='y'){
node->total +=100;
printf("\nFast delivery applied\nTotal %.2f",node->total);
insert_at_start(node);
}
else{
printf("\nTotal: %.2f",node->total);
insert_at_end(node);
}
}
void display_list(){
printf("\nBill No\t\tOrder Item\t\tCname\t\tQ\t\tTotal");
struct bill_item* ptr = head;
ptr = ptr->next;
while(ptr->next!=NULL){
printf("\n%d\t\t%d\t\t%s\t\t%d\t\t%.2f",ptr->bill_no,ptr->order_item_no,ptr->customer_name,ptr->quantity,ptr->total);
ptr = ptr->next;
}
}
I have tried to find the errors. But can't point out any. The errror is somewhere at the functions insert_at_end() and insert_at_start()
In display_list(), if head->next is NULL, you try to read the ptr->next without first checking if it's null:
ptr = ptr->next;
while(ptr->next != NULL) {
// ...
}
This will segfault because ptr is null.

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);
}

How can I add Lchild and Rchild to my existing nodes?

I have the following C program that adds Nodes to a tree and then the user can select a sorting method. How can I modify the program in a manner that will allow me to add a LChild and RChild to every node? Any help is highly appreciated since I am completely new to BSTs.
Writiong this because apparently my post is mostly code
Code:
#include <stdio.h>
#include <stdlib.h>
struct treenode {
struct treenode *lchild;
struct treenode *rchild;
int data;
} *root = NULL;
void insertnode(struct treenode **pp,int d)
{
for( ;*pp; )
{
if (d < (*pp)->data) pp = &(*pp)->lchild;
else pp = &(*pp)->rchild;
}
*pp = malloc (sizeof **pp);
(*pp)->data = d;
(*pp)->lchild = NULL;
(*pp)->rchild = NULL;
}
void preorder(struct treenode *p)
{
if(p==NULL)
{
printf("\nThe list is empty");
return;
}
printf("%d,",p->data);
if (p->lchild) preorder(p->lchild);
if (p->rchild) preorder(p->rchild);
}
void postorder(struct treenode *p)
{
if(p==NULL)
{
printf("\nThe list is empty");
return;
}
if (p->lchild) preorder(p->lchild);
if (p->rchild) preorder(p->rchild);
printf("%d,",p->data);
}
void inorder(struct treenode *p)
{
if(p==NULL)
{
printf("\nThe list is empty");
return;
}
if (p->lchild) preorder(p->lchild);
printf("%d,",p->data);
if (p->rchild) preorder(p->rchild);
}
int main(void)
{
root=NULL;
int choice,data;
while(1)
{
printf("\nPress 1 for inserting a node in BST fashion: ");
printf("\nPress 2 for traversing the tree in preorder fashion :");
printf("\nPress 3 for traversing the tree in postorder fashion :");
printf("\nPress 4 for traversing the tree in inorder fashion :");
printf("\nPress 5 to exit :");
printf("\nEnter your choice: ");
scanf("%d", &choice);
switch(choice)
{
case 1: printf("\nEnter the data to be inserted:");
scanf("%d",&data);
insertnode( &root,data);
break;
case 2: preorder(root);
break;
case 3: postorder(root);
break;
case 4: inorder(root);
break;
case 5: exit(0);
break;
default: printf("\nYou have entered an invalid choice. Please try again");
}
}
return 0;
}
when a new value added to BST,then it check the conditions such that if value ">" the current node value then its we move to the right child of the node and if value "<" then we move to the left child of the node,we do this untill we get to leaf node.
As for your case,just change for condition with while conditions and check if it works.
void insertnode(struct treenode **pp,int d)
{
while((*pp)->data == NULL)
{
if (d < (*pp)->data)
pp = &(*pp)->lchild;
else
pp = &(*pp)->rchild;
}
*pp = malloc (sizeof **pp);
(*pp)->data = d;
(*pp)->lchild = NULL;
(*pp)->rchild = NULL;
}

Printing strings in linked lists

So I'm having trouble getting my program to print both the strings I input, or however many you want to put in the list, it always prints out the last string inputted multiple times. I am sorry about all the commented out code, most of it you don't need to read.
#include<stdio.h>
#include<stdlib.h>
struct node{
char *data;
struct node *next;
}*head;
typedef struct node NODE;
// Function prototypes
void append(char myStr[]);
void add( char myStr[] );
//void addafter(char myStr[], int loc);
void insert(char myStr[]);
int delete(char myStr[]);
void display(struct node *r);
int count();
// main function
int main()
{
int i;
struct node *n;
head = NULL;
char myStr[50];
while(1)
{
printf("\nList Operations\n");
printf("===============\n");
printf("1.Insert\n");
printf("2.Display\n");
printf("3.Size\n");
printf("4.Delete\n");
printf("5.Exit\n");
printf("Enter your choice : ");
if(scanf("%d", &i) <= 0)
{
printf("Enter only an Integer\n");
exit(0);
}
else
{
switch(i)
{
case 1:
printf("Enter the name to insert : ");
scanf("%50s", myStr);
insert(myStr);
break;
case 2:
if(head == NULL)
{
printf("List is Empty\n");
}
else
{
printf("Name(s) in the list are : ");
}
display(n);
break;
case 3:
printf("Size of the list is %d\n",count());
break;
case 4:
if(head == NULL)
printf("List is Empty\n");
else
{
printf("Enter the myStrber to delete : ");
scanf("%50s",myStr);
if(delete(myStr))
printf("%s deleted successfully\n",myStr);
else
printf("%s not found in the list\n",myStr);
}
break;
case 5:
return 0;
default:
printf("Invalid option\n");
}
}
}
return 0;
}
// Function definitions
void append(char myStr[])
{
struct node *temp,*right;
temp = (struct node *)malloc(sizeof(struct node));
temp->data = myStr;
right=(struct node *)head;
while(right->next != NULL)
{
right = right->next;
}
right->next = temp;
right = temp;
right->next = NULL;
}
// adding a node to the beginning of the linked list
void add( char myStr[] )
{
struct node *temp;
temp =(struct node *)malloc(sizeof(struct node));
temp->data = myStr;
// only one node on the linked list
if (head == NULL)
{
head = temp;
head->next = NULL;
}
else
{
temp->next = head;
head = temp;
}
}
void insert(char myStr[])
{
int c = 0;
struct node *temp;
temp = head;
if(temp == NULL)
{
add(myStr);
}
else
{
append(myStr);
}
}
int delete(char myStr[])
{
struct node *temp, *prev;
temp = head;
while(temp != NULL)
{
if(temp->data == myStr)
{
if(temp == head)
{
head = temp->next;
head = (*temp).next;
free(temp);
return 1;
}
else
{
prev->next = temp->next;
free(temp);
return 1;
}
}
else
{
prev = temp;
temp = temp->next;
}
}
return 0;
}
void display(struct node *r)
{
r = head;
if(r == NULL)
{
return;
}
while(r != NULL)
{
printf("%s ", r->data);
r = r->next;
if(r == NULL)
{
printf("\nOur linked list is finished!");
}
}
printf("\n");
}
int count()
{
struct node *n;
int c = 0;
n = head;
while(n != NULL)
{
n = n->next;
c++;
}
return c;
}
The problem seems to be that myStr at main function is a char[], so it's content is overritten every time you insert data. Notice that struct node data field is a char*, it's just pointing to myStr address.
Hope this help!
Your program has only one place to write your input, myStr.
With each input, myStr is erased and a something else is written to myStr.
The data member of all of the nodes, points to myStr. myStr will only contain the last input.
The display() function asks each node what is data. data points to myStr so each node prints the contents of myStr. myStr will only contain the last input so all the nodes print the last input.
To fix this, in the add() and append() functions, you need to give the data member some memory by using malloc(). Then copy the contents of myStr to the data member by using strcpy().
temp->data = malloc ( strlen ( myStr) + 1);
strcpy ( temp->data, myStr);
Do this instead of temp->data = myStr;
You will need #include<string.h>
The memory will need to be free()'d in the delete() function.
free(temp->data);
Do this before freeing temp
char *data
that variable from struct is always assigned with the address of myStr as its a pointer it would only show you the value of myStr

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