Cant find error in my Code? C - c

The idea is to be able to add a name to the end of the linked list when the user enters "1" and print and delete the first name in the linked list when the user enters "0". This is working if there is only 2 names in the linked list but anymore than 2 it only does the first name and last name, yet I cannot see my error.
#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
#define bool int
#define TRUE 1d
#define FALSE 0
typedef struct node{
char name[100];
struct node *next;
} Node;
Node *head;
void call(){
if(head == NULL){
printf("List is empty.\n");
}
else{
Node *temp;
printf("Calling %s\n", head->name);
if(head->next!=NULL){
temp = head->next;
free(head);
head = temp;
}
else{
head = NULL;
}
}
}
void add(char input[]){
Node *temp;
temp = (Node*)malloc(sizeof(Node));
strcpy(temp->name, input);
temp->next = NULL;
if(head == NULL){
head = temp;
}
else{
head->next = temp;
}
}
int main(){
start:;
int user_menu_answer;
char waste;
printf("-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\n");
printf("0) Call a customer\n");
printf("1) Add a customer\n");
printf("2) Quit\n");
printf("Please input your command \n");
printf("-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\n");
scanf("%d%c", &user_menu_answer, &waste);
//main menu options
if(user_menu_answer == 0){
call();
goto start;
}
else if (user_menu_answer == 1){
char input[23];
printf("Please give me the customers name: \n");
scanf("%[^\n]", input);
add(input);
goto start;
}
else if (user_menu_answer == 2){
printf("Quitting...");
return 0;
}
else{
printf("You did not enter a valid option, Please try again. \n");
goto start;
}
}

First MISTAKE:
void call(){
if(head == NULL){
printf("List is empty.\n");
}
else{
Node *temp;
printf("Calling %s\n", head->name);
if(head->next!=NULL){
temp = head->next;
free(head);
head = temp;
}
else{
free(head); //you don't free the memory if it's just one in the list
head = NULL;
}
}
}
Second mistake:
void add(char input[]){
Node *AuxHead; //create an aux to the head so you can move threw the list
Node *temp;
temp = (Node*)malloc(sizeof(Node));
if(temp!=NULL) //verify if it got allocated
{
strcpy(temp->name, input);
temp->next = NULL;
if(head == NULL){
head = temp;
}
else{
AuxHead=head; //pass the address of the head
while(AuxHead->next!=NULL) //catch the lest node of the list
AuxHead=AuxHead->next;
AuxHead->next = temp; //make the temp, the last of the list
}
}
}

Related

Correct way to delete a node in doubly circular linked list

The purpose of this code is to manage insertion and deletion and visualisation. I just want to know if I'm doing everything correctly, let me know if there are more possible ways to do this. This is my first attempt, i didn't follow any tutorial.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct Node {
int n;
struct Node *next;
struct Node *prev;
}TNode;
typedef TNode* Node;
void NewNode(Node *pp, int n)
{
Node temp, last;
temp = (Node)malloc(sizeof(struct Node));
temp->n = n;
temp->next = temp;
temp->prev = temp;
if(*pp != NULL)
{
last = (*pp)->prev;
temp->next = (*pp);
temp->prev = last;
last->next = (*pp)->prev = temp;
}
*pp = temp;
}
void ViewList(Node head)
{
if(head == NULL)
{
return;
}
Node node = head->prev;
do
{
printf("Curr: %d\n", node->n);
node = node->prev;
}while(node != head->prev);
}
void ReadData(Node * head, int * n)
{
printf("\nInsert a number:");
scanf("%d", n);
NewNode(head, *n);
}
Node SearchNode(Node head)
{
int d;
printf("\nElement to Delete:");
scanf("%d", &d);
while(head != NULL)
{
if(head->n == d)
{
return head;
}
head = head->next;
}
printf("\nNo Element [%d] Found", d);
return NULL;
}
void Delete(Node * head)
{
Node del = SearchNode(*head);
if(*head == NULL || del == NULL)
{
return;
}
if(*head == del && del->next == *head)
{
*head = NULL;
free(del);
return;
}
if(*head == del)
{
*head = del->next;
del->prev->next = *head;
(*head)->prev = del->prev;
free(del);
return;
}
if((*head)->prev == del)
{
(*head)->prev = del->prev;
del->prev->next = *head;
free(del);
return;
}
del->next->prev = del->prev;
del->prev->next = del->next;
free(del);
}
int Menu()
{
int c;
printf("\n*** M E N U ***\n"
"1 - New Node\n"
"2 - View List\n"
"3 - Delete\n"
"0 - Exit\n"
"\n>> ");
scanf(" %d", &c);
return c;
}
int main()
{
int c,n;
Node head = NULL;
do {
c = Menu();
switch (c)
{
case 1: ReadData(&head, &n); break;
case 2: ViewList(head); break;
case 3: Delete(&head); break;
default: c = 0;
}
} while (c != 0);
return 0;
}
How can i test if this is a real circular doubly linked list and not a simple doubly linked list?
Your program works fine, the only real bug I detected is in SearchNode: if the element is not present in the list, you enter an infinite loop. Your list is obviously a circular list and therefore you need to check if you have got back to the head in the function, which means that the element you're searching for is not in the list:
Corrected version:
Node SearchNode(Node head)
{
int d;
printf("\nElement to Delete:");
scanf("%d", &d);
Node start = head; // remember where we started
while (head != NULL)
{
if (head->n == d)
{
return head;
}
head = head->next;
if (head == start) // if we are back to where we started
break; // the element hasn't been found and we stop the loop
}
printf("\nNo Element [%d] Found", d);
return NULL;
}
There are also some design flaws, that don't prevent the program from working correctly:
One of them is this: The n variable is not used outside ReadData, so it's pointless to declare it in main and pass it's pointer to ReadData.
Corrected version:
void ReadData(Node * head)
{
int n; // declare n locally
printf("\nInsert a number:");
scanf("%d", &n);
NewNode(head, n);
}
Call it like this: ReadData(&head) and remove int n; from main.

Segmentation fault using argv[1]

I created a code that inserts and deletes nodes from a Linked List depending on what a .txt file instructs. I previously used scanf("%s",fname) to open the file but now I want to open it using the command line, specifically argv[1] == file name to open it and read from it. Now that I decided to use this I keep getting a segmentation fault. Any ideas why this is occurring? I just started taking a C course in my University and am brand new to it.
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
typedef struct node{
int val;
struct node *next;
} Node;
void count_node(Node *head){
Node *temp;
int i=0;
temp = head;
while(temp!=NULL){
i++;
temp=temp->next;
}
printf("number of nodes are %d \n ",i);
}
void displayList(Node *head){
Node *temp;
temp = head;
while(temp != NULL){
printf(" %d ",temp->val);
temp = temp->next;
}
}
Node * findBefore(Node *head,int value){
Node *curr = head;
Node *prev = NULL;
while(curr != NULL){
if(value <= curr->val){
return prev;
}
prev = curr;
curr = curr->next;
/*printf("a\n");
break;*/
}
return prev; // 1 2 4
//printf("b\n");
}
void add(Node *head,int newValue){ //return a Node 0 for some reason
ask TA
printf("check \n");
Node *newNode = malloc(sizeof(Node));
if(newNode == NULL){
printf("check \n");
return;
}
newNode->val = newValue;
//if list is empty:
if(head == NULL){
printf("check \n");
head = newNode;
}
//if list is not empty:
Node *prev = findBefore(head,newNode->val); //a -> b
if(prev == NULL){
printf("check \n");
newNode->next = head;
head = newNode;
return;
}
printf("check \n");
Node *temp = prev->next;
prev->next = newNode;
newNode->next = temp;
}
void delete(Node *head, int delVal){
if(head == NULL){
return;
}
Node *prev = NULL;
Node *curr = head;
if(delVal == curr->val && prev !=NULL ){ // 1 2
prev->next = curr->next;
free(curr);
return;
}
else if(delVal == curr->val && prev == NULL){ // 1
head = NULL;
free(curr);
return;
}
while(curr != NULL) {
while(curr != NULL && curr->val != delVal){
prev = curr;
curr = curr->next;
}
if (curr == NULL){
return;
}
prev->next = curr->next;
free(curr);
curr = prev->next;
}
}
int main(int argc,char *argv[]) {
FILE * fp;
char singleLine[150];
char command;
int val;
fp = fopen(argv[1],"r");
if(fp == NULL ){
exit(1);
}
Node *head = malloc(sizeof(Node));
if(head == NULL){ //malloc returns null is there is a memory leak
return 1;
}
while(fgets(singleLine,100,fp)){
//printf("%s\n",singleLine);
sscanf(singleLine,"%c %d",&command,&val);
//printf("command character is: %c\n" , command);
//printf("The value we have to add is: %d\n",val);
if(command == 'i'){
printf("Found i, and add %d\n",val);
add(head,val);
}
else if(command == 'd'){
delete(head,val);
printf("found d and delete %d\n",val);
}
}
free(head);
fclose(fp);
printf("\n");
count_node(head);
printf("The linked list is : \n ");
displayList(head);
return 0;
}
What is the command you are using to run the program? Especially in larger projects, when we need to deal with external input, it's good practice to check it's validity.
Maybe something like:
if (argc < 2) {
println("Invalid input: No arguments");
return 1;
}
char *filename = argv[1];
fp = fopen(filename,"r");
To see what may be the reason the call is failing. Try to add this short debug code before your call to argv[1]:
println("Number of arguments: %d", argc);
for (int i = 0, i < argc, i++) {
println("Argument %d: \"%s\"", i, argv[i]);
}

linked list using double pointers

Using double pointers first time to create and display linked list
#include "stdio.h"
#include "stdlib.h"
struct node
{
int data;
struct node * next;
};
void Insert(struct node **, int , int );
void display(struct node *);
int main()
{
int c, data, position;
struct node* head;
do{
printf("Enter a choice :\n");
printf("1. Add an element.\n");
printf("2. Del an element.\n3.Display List.\n");
printf("4.Delete linked list.\n5.Exit.\n");
printf("Your Choice :");
scanf("%d",&c);
switch(c){
case 1 :
printf("\nEnter data and position :\n");
scanf("%d %d",&data,&position);
Insert(&head,data,position);
break;
case 2 :
break;
case 3 :
printf("Linked List : \n");
display(head);
break;
case 4 :
break;
case 5 :
exit(0);
default :
printf("Invalid Choice.\n");
break;
}
}while(1);
return 0;
}
void Insert(struct node **ptrhead, int item, int position){
struct node *p,*newnode;
//node creation.
newnode = (struct node *)malloc(sizeof(struct node));
if (!newnode)
{
printf("Memory Error.\n");
return;
}
newnode->next = NULL;
newnode->data = item;
p = *ptrhead;
// Creates initial node
if (!(p->data))
{
p = newnode;
}
// insertion at beginning
if (position==1)
{
newnode->next = p;
p = newnode;
free(newnode);
}
// insertionn at middle or end.
else
{
int i=1;
while(p->next!=NULL && i<position-1){
p=p->next;
i++;
}
newnode->next = p->next;
p->next = newnode;
}
*ptrhead = p;
};
// Display Linked list
void display(struct node *head){
if (head)
{
do{
printf("%d\n", head->data);
head = head->next;
}while(head->next);
}
};
I will add functions for deletion and other operations later. Right now , I just want to insert and display fns to work . But output comes as infinitely running loop with wrong values. I cannot figure out what's wrong in my code , please help ?
Thanks in advance.
Not sure why somebody would be writing this type of C today, looks like maybe I'm doing your homework for you... In any case, you asked to fix your code, not rewrite it, so here's the minimum set of changes.
head should be initialized to NULL.
if (!(p->data)) is not right. That if statement should just be:
// Creates initial node
if (!p)
{
*ptrhead = newnode;
return;
}
Remove free(newnode);.
The insert at middle/end code could be
int i = 1;
struct node *n = p;
while (n->next != NULL && i<position - 1){
n = n->next;
i++;
}
newnode->next = n->next;
n->next = newnode;
The final insert function:
void Insert(struct node **ptrhead, int item, int position)
{
struct node *p, *newnode;
//node creation.
newnode = (struct node *)malloc(sizeof(struct node));
if (!newnode)
{
printf("Memory Error.\n");
return;
}
newnode->next = NULL;
newnode->data = item;
p = *ptrhead;
// Creates initial node
if (!p)
{
*ptrhead = newnode;
return;
}
// insertion at beginning
if (position == 1)
{
newnode->next = p;
p = newnode;
}
// insertionn at middle or end.
else
{
int i = 1;
struct node *n = p;
while (n->next != NULL && i<position - 1){
n = n->next;
i++;
}
newnode->next = n->next;
n->next = newnode;
}
*ptrhead = p;
}
Your print function isn't quite right, just make it:
// Display Linked list
void display(struct node *head)
{
while (head)
{
printf("%d\n", head->data);
head = head->next;
}
}

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

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

Resources