Linked list add() method in C - c

Where is error the following code?
addNode() function is not run, neither is the traverse() function.
Last data is not shown.
#include <stdio.h>
#include <stdlib.h>
struct isimler{
char isim[10];
struct isimler *next;
};
typedef struct isimler node;
node *head;
void createList(){
int k, n;
node *po;
printf("Eleman Sayisi: "); scanf("%d", &n);
for(k = 0; k<n; k++){
if(k == 0){
head = (node *) malloc(sizeof(node));
po = head;
}else{
po->next = (node *) malloc(sizeof(node));
po = po->next;
}
printf("Isim Girin: "); scanf("%s",po->isim);
}
po->next = NULL;
}
void addNode(){
node *po, *newNode;
po = head;
while(po != NULL){
po = po->next;
}
po = (node *) malloc(sizeof(node));
printf("Isim Girin: "); scanf("%s", po->isim);
po->next = NULL;
}
void traverseList(){
node *po;
int i=0;
po = head;
while(po != NULL){
printf("%d.\t%s\n",i,po->isim);
po = po->next;
i++;
}
}
int main(){
createList();
traverseList();
addNode();
traverseList();
return 1903;
}

Your current addNode() method creates a new node but it doesn't add it to your linked list.
You need to modify your addNode() method like so:
void addNode(){
node *po, *newNode;
po = head;
while(po->next != NULL) { // change this so you don't lose the end of the list
po = po->next; // po is now pointing to the last node in the list
}
newNode = (node *) malloc(sizeof(node)); // change this to newNode
printf("Isim Girin: "); scanf("%s", newNode->isim);
po->next = newNode; // add the new node here, don't set it to NULL
newNode->next = NULL;
}

You can have look this code and get to know where exactly you are having problem
#include<stdio.h>
#include<stdlib.h>
#include<stdbool.h>
struct test_struct
{
int val;
struct test_struct *next;
};
struct test_struct *head = NULL;
struct test_struct *curr = NULL;
struct test_struct* create_list(int val)
{
printf("\n creating list with headnode as [%d]\n",val);
struct test_struct *ptr = (struct test_struct*)malloc(sizeof(struct test_struct));
if(NULL == ptr)
{
printf("\n Node creation failed \n");
return NULL;
}
ptr->val = val;
ptr->next = NULL;
head = curr = ptr;
return ptr;
}
struct test_struct* add_to_list(int val, bool add_to_end)
{
if(NULL == head)
{
return (create_list(val));
}
if(add_to_end)
printf("\n Adding node to end of list with value [%d]\n",val);
else
printf("\n Adding node to beginning of list with value [%d]\n",val);
struct test_struct *ptr = (struct test_struct*)malloc(sizeof(struct test_struct));
if(NULL == ptr)
{
printf("\n Node creation failed \n");
return NULL;
}
ptr->val = val;
ptr->next = NULL;
if(add_to_end)
{
curr->next = ptr;
curr = ptr;
}
else
{
ptr->next = head;
head = ptr;
}
return ptr;
}
struct test_struct* search_in_list(int val, struct test_struct **prev)
{
struct test_struct *ptr = head;
struct test_struct *tmp = NULL;
bool found = false;
printf("\n Searching the list for value [%d] \n",val);
while(ptr != NULL)
{
if(ptr->val == val)
{
found = true;
break;
}
else
{
tmp = ptr;
ptr = ptr->next;
}
}
if(true == found)
{
if(prev)
*prev = tmp;
return ptr;
}
else
{
return NULL;
}
}
int delete_from_list(int val)
{
struct test_struct *prev = NULL;
struct test_struct *del = NULL;
printf("\n Deleting value [%d] from list\n",val);
del = search_in_list(val,&prev);
if(del == NULL)
{
return -1;
}
else
{
if(prev != NULL)
prev->next = del->next;
if(del == curr)
{
curr = prev;
}
else if(del == head)
{
head = del->next;
}
}
free(del);
del = NULL;
return 0;
}
void print_list(void)
{
struct test_struct *ptr = head;
printf("\n -------Printing list Start------- \n");
while(ptr != NULL)
{
printf("\n [%d] \n",ptr->val);
ptr = ptr->next;
}
printf("\n -------Printing list End------- \n");
return;
}
int main(void)
{
int i = 0, ret = 0;
struct test_struct *ptr = NULL;
print_list();
for(i = 5; i<10; i++)
add_to_list(i,true);
print_list();
for(i = 4; i>0; i--)
add_to_list(i,false);
print_list();
for(i = 1; i<10; i += 4)
{
ptr = search_in_list(i, NULL);
if(NULL == ptr)
{
printf("\n Search [val = %d] failed, no such element found\n",i);
}
else
{
printf("\n Search passed [val = %d]\n",ptr->val);
}
print_list();
ret = delete_from_list(i);
if(ret != 0)
{
printf("\n delete [val = %d] failed, no such element found\n",i);
}
else
{
printf("\n delete [val = %d] passed \n",i);
}
print_list();
}
return 0;
}

Related

I was trying to make a simple doubly linked list with operations Insert, Delete and Display and

The insert seems to go smoothly but the display only shows the head element only. I wanted to do this on my own and tried to use the logic. I am confused whether the fault lies in the Insert function or the Display.
I am not really that great at programming and just started learning C++.Thank you for your help.
#include <stdio.h>
#include <stdlib.h>
struct node
{
int data;
struct node *prev;
struct node *next;
};
struct node *head = NULL;
void insert(struct node **head)
{
struct node *newnode = (struct node *)malloc(sizeof(struct node));
newnode->next = NULL;
newnode->prev = NULL;
if ((*head) == NULL)
{
int x;
printf("\nEnter the value of the starting node :");
scanf("%d", &x);
newnode->data = x;
(*head) = newnode;
}
else
{
int pos, x;
printf("\nEnter the pos ");
scanf("%d", &pos);
if (pos == 0)
{
newnode->next = (*head);
newnode->prev = NULL;
(*head)->prev = newnode;
(*head) = newnode;
printf("\nEnter data in %d pos : ", pos);
scanf("%d", &x);
newnode->data = x;
}
else
{
struct node *temp;
struct node *ptr = (*head);
while(ptr->next!=NULL)
{
for (int i = 0; i < pos - 1; i++)
{ ptr = ptr->next;}
}
if (ptr->next == NULL)
{
newnode->prev = ptr;
newnode->next = NULL;
printf("\nEnter data in %d pos : ", pos);
scanf("%d", &x);
newnode->data = x;
}
else
{
printf("\nEnter data in %d pos : ", pos);
scanf("%d", &x);
newnode->data = x;
temp = ptr->next;
newnode->prev = ptr;
newnode->next = temp;
ptr->next = newnode;
temp->prev = newnode;
}
}
}
}
void delete (struct node **head)
{
struct node *ptr;
ptr = (*head);
if ((*head) == NULL)
{
printf("\nUnderflow\n");
}
else
{
int pos;
printf("\nEnter the pos ");
scanf("%d", &pos);
struct node *temp;
for (int i = 0; i < pos; i++)
{
ptr = ptr->next;
}
temp = ptr->next;
temp->prev = ptr->prev;
ptr->next = NULL;
ptr->prev = NULL;
}
}
void display(struct node **head)
{
struct node *ptr = (*head);
if (ptr != NULL)
{
printf(" %d ",ptr->data);
}
else
{
printf("\nUnderflow OR empty\n");
}
}
int main()
{
while (1)
{
int x;
printf("\n1.Insert\n2.Delete\n3.Display\n4.Exit\n\nChoose option :\n");
scanf("%d", &x);
switch (x)
{
case 1:
{
insert(&head);
break;
}
case 2:
{
delete (&head);
break;
}
case 3:
{
display(&head);
break;
}
default:
{
printf("\nWrong operation.Select again :");
continue;
}
}
}
return 0;
}
The display was supposed to show the list like
a-> b -> c......
In the display function you should take the next node and print that too
// head->next1->next2->NULL
struct node *ptr = (*head);
while (ptr != NULL) {
printf("%d->", ptr->data);
ptr = ptr->next;
}
printf("NULL");

Linked list value pointed only changing inside function in C

I am trying to implement a linked list in C:
struct Node{
struct Node *next;
void *data;
};
With an insert function:
void insert(void *p2Node, void *data)
{
struct Node *newNode;
struct Node **p2p2Node= (struct Node **)p2Node;
if (newNode = malloc(sizeof(struct Node))) /* if successfully allocated */
{
newNode->data = data;
if ((*p2p2Node) != NULL) /* if the list is not empty */
{
newNode->next = (*p2p2Node)->next;
(*p2p2Node)->next = newNode;
}
else
(*p2p2Node) = newNode;
p2Node = p2p2Node;
}
printf("Inside the insert: %s\n", (*p2p2Node)->data);
}
I called insert in main():
int main()
{
char *setA = "liquid ";
char *setB = " lgd";
char *setC = "sample";
struct Node *nList = malloc(sizeof(struct Node));
insert(nList, setC);
printf("2Get %s\n", nList->data);
return 0;
}
No error or warning was reported, but the value was only changed inside the insert. Back to main() the linked list is still empty.
I do not understand: nList in main() is a void pointer. Inside insert(), *p2Node is not altered, I used p2p2Node to change the value p2Node points to, why is it not working? Did I mismatch the pointers? Is there a way I can make it work without modifying the parameter of insert()?
Thank you.
Use this code to insert values to the linked list.
struct node{
int data;
struct node* link;
};
struct node *root = NULL;
int len;
int main()
{
append();
display();
addatbegin();
display();
addatafter();
display();
}
Add values to the end of the list.
void append(){
struct node* temp;
temp = (struct node*)malloc(sizeof(struct node));
printf("Enter the data: ");
scanf("%d", &temp->data);
temp->link = NULL;
if(root == NULL) //list is empty
{
root=temp;
}else
{
struct node* p;
p=root;
while(p->link != NULL)
{
p = p->link;
}
p->link = temp;
}
}
Add values to the beginning of the list.
void addatbegin()
{
struct node* temp;
temp = (struct node*)malloc(sizeof(struct node));
printf("Enter the data : ");
scanf("%d", &temp->data);
temp->link = NULL;
if(root == NULL)
{
temp = root;
}
else
{
temp->link = root;
root = temp;
}
}
Add value after a node
void addatafter()
{
struct node* temp, *p;
int loc, i=1;
printf("Enter the location : ");
scanf("%d", &loc);
if(loc > len)
{
printf("Invalid input.");
}
else
{
p = root;
while(i > loc)
{
p = p->link;
i++;
}
temp = (struct node*)malloc(sizeof(struct node));
printf("Enter the data : ");
scanf("%d", &temp->data);
temp->link = NULL;
temp->link = p->link;
p->link = temp;
}
}
To display the linked list
void display(){
struct node* temp;
temp = root;
if(temp == NULL)
{
printf("List id empty.\n");
}
else
{
while (temp != NULL){
printf("%d -> ", temp->data);
temp = temp->link;
}
printf("\n\n");
}
}

Add element linked list

#include <stdio.h>
#include <stdlib.h>
typedef struct str_node {
int data;
struct str_node *next;
} node;
void create_list(node ** head, int n);
void display_list(node * head);
void add_e(node ** head);
int
main(void)
{
int n;
node *head;
head = NULL;
printf("Insert size of list: ");
scanf("%d",&n);
create_list(&head, n);
display_list(head);
add_e(&head);
display_list(head);
return 0;
}
void
display_list(node *head)
{
if (head == NULL) {
printf("Empty list.");
}
else {
while (head != NULL) {
printf("DATA: %d\n", head->data);
head = head->next;
}
puts("null");
}
}
void create_list(node **head,int n){
node *new,*tmp;
int num,i;
*head = malloc(sizeof(node));
if(*head == NULL){
printf("Memory can not be allocated.");
}
else{
printf("Insert element 1: ");
scanf("%d",&num);
(*head)->data = num;
(*head)->next = NULL;
tmp = *head;
for(i=2;i<=n;i++){
new = malloc(sizeof(node));
if(new == NULL){
printf("Memory can not be allocated.");
break;
}
else{
printf("Insert element %d: ",i);
scanf("%d",&num);
new->data = num;
new->next = NULL;
tmp->next = new;
tmp = tmp->next;
}
}
}
}
void
add_e(node **head)
{
node *new;
int num;
new = malloc(sizeof(node));
if (new == NULL) {
printf("Memory can not be allocated.");
}
else {
printf("Insert element at the beginnig: ");
scanf("%d", &num);
new->data = num;
new->next = NULL;
while ((*head)->next != NULL) {
*head = (*head)->next;
}
(*head)->next = new;
}
}
I don't understand why after using the add_e() function, the display_list() function gives to me only the last two number of the list. The add_e() fucntion should be add an element at the end of the list. What am i doing wrong?
Edit: Added create_list() function so you can understand better but now it says to me to add more details so I'm writing something.
In main, n is unitialized, so you'll get random/bad results.
The add_e should not use *head in the while or even do a while. The printf says "insert at beginning", which is different/simpler. This is what I've currently coded up/fixed.
You'd want to use a loop, if you [really] wanted to insert/append to the end of the list. But, the loop would still be incorrect, because you don't want to advance head when finding the end.
I've also fixed the printf for prompts and scanf
Here's a refactored/fixed version of your code with the bugs annotated:
#include <stdio.h>
#include <stdlib.h>
typedef struct str_node {
int data;
struct str_node *next;
} node;
void create_list(node **head, int n);
void display_list(node *head);
void add_e(node ** head);
int
main(void)
{
int n;
node *head;
head = NULL;
// NOTE/BUG: n is unitialized
#if 1
n = 5;
#endif
create_list(&head, n);
display_list(head);
add_e(&head);
display_list(head);
return 0;
}
void
display_list(node *head)
{
if (head == NULL) {
printf("Empty list.");
}
else {
while (head != NULL) {
printf("DATA: %d\n", head->data);
head = head->next;
}
puts("null");
}
}
void
create_list(node **head, int n)
{
node *new,
*tmp;
int num,
i;
*head = malloc(sizeof(node));
if (*head == NULL) {
printf("Memory can not be allocated.");
}
else {
printf("Insert element 1: ");
#if 1
fflush(stdout);
#endif
#if 0
scanf("%d", &num);
#else
scanf(" %d", &num);
#endif
(*head)->data = num;
(*head)->next = NULL;
tmp = *head;
for (i = 2; i <= n; i++) {
new = malloc(sizeof(node));
if (new == NULL) {
printf("Memory can not be allocated.");
break;
}
else {
printf("Insert element %d: ", i);
#if 1
fflush(stdout);
#endif
#if 0
scanf("%d", &num);
#else
scanf(" %d", &num);
#endif
new->data = num;
new->next = NULL;
tmp->next = new;
tmp = tmp->next;
}
}
}
}
void
add_e(node **head)
{
node *new;
int num;
new = malloc(sizeof(node));
if (new == NULL) {
printf("Memory can not be allocated.");
}
else {
printf("Insert element at the beginnig: ");
fflush(stdout);
scanf(" %d", &num);
new->data = num;
new->next = NULL;
#if 0
while ((*head)->next != NULL) {
*head = (*head)->next;
}
(*head)->next = new;
#else
if (*head == NULL)
*head = new;
else {
new->next = *head;
*head = new;
}
#endif
}
}
UPDATE:
In add_e, because I couldn't be sure if you wanted to insert at beginning of list [based on the printf] or at the end [based on the code], I created a version that is cleaned up a bit more and demonstrates both types:
#include <stdio.h>
#include <stdlib.h>
typedef struct str_node {
int data;
struct str_node *next;
} node;
void create_list(node **head, int n);
void display_list(node *head);
void add_begin(node **head);
void add_end(node **head);
int
main(void)
{
int n;
node *head;
setbuf(stdout,NULL);
head = NULL;
printf("Enter initial number of list elements: ");
scanf(" %d",&n);
create_list(&head, n);
display_list(head);
add_begin(&head);
display_list(head);
add_end(&head);
display_list(head);
return 0;
}
void
display_list(node *head)
{
node *cur;
if (head == NULL) {
printf("Empty list.\n");
}
for (cur = head; cur != NULL; cur = cur->next)
printf("DATA: %d\n", cur->data);
}
void
create_list(node **head, int n)
{
node *new, *tmp;
int num, i;
tmp = *head;
for (i = 1; i <= n; i++) {
new = malloc(sizeof(node));
if (new == NULL) {
printf("Memory can not be allocated.");
break;
}
printf("Insert element %d: ", i);
scanf(" %d", &num);
new->data = num;
new->next = NULL;
if (*head == NULL)
*head = new;
else
tmp->next = new;
tmp = new;
}
}
// add_begin -- insert at before head of list
void
add_begin(node **head)
{
node *new;
int num;
new = malloc(sizeof(node));
if (new == NULL) {
printf("Memory can not be allocated.");
exit(1);
}
printf("Insert element at the beginning: ");
scanf(" %d", &num);
new->data = num;
new->next = *head;
*head = new;
}
// add_end -- add to tail/end of list
void
add_end(node **head)
{
node *new;
node *tmp;
node *tail;
int num;
new = malloc(sizeof(node));
if (new == NULL) {
printf("Memory can not be allocated.");
exit(1);
}
printf("Append element at the end: ");
scanf(" %d", &num);
new->data = num;
new->next = NULL;
// find the tail
tail = NULL;
for (tmp = *head; tmp != NULL; tmp = tmp->next)
tail = tmp;
if (tail != NULL)
tail->next = new;
else
*head = new;
}

a singly linked list for all data types, implement insertion, delete and find an element in C language

so i have managed to come up with a syntax for only integers. how do i write the syntax for all data types most preferrably using typedef and void* as well would like to know now to use the void push_back command.?
it creates a linked list, adds nodes, deletes nodes and finds any nodes with in the list.
The first node is always made accessible through a global ‘head’ pointer. This pointer is adjusted when first node is deleted.
Similarly there is a ‘curr’ pointer that contains the last node in the list. This is also adjusted when last node is deleted.
Whenever a node is added to linked list, it is always checked if the linked list is empty then add it as the first node.
Is there anyother way to add,delete and find nodes in a linked list without using #include<stdbool.h> ?
#include<stdio.h>
#include<stdlib.h>
#include<stdbool.h>
struct test_struct
{
int val;
struct test_struct *next;
};
struct test_struct *head = NULL;
struct test_struct *curr = NULL;
struct test_struct* create_list(int val)
{
printf("\n creating list with headnode as [%d]\n",val);
struct test_struct *ptr = (struct test_struct*)malloc(sizeof(struct test_struct));
if(NULL == ptr)
{
printf("\n Node creation failed \n");
return NULL;
}
ptr->val = val;
ptr->next = NULL;
head = curr = ptr;
return ptr;
}
struct test_struct* add_to_list(int val, bool add_to_end)
{
if(NULL == head)
{
return (create_list(val));
}
if(add_to_end)
printf("\n Adding node to end of list with value [%d]\n",val);
else
printf("\n Adding node to beginning of list with value [%d]\n",val);
struct test_struct *ptr = (struct test_struct*)malloc(sizeof(struct test_struct));
if(NULL == ptr)
{
printf("\n Node creation failed \n");
return NULL;
}
ptr->val = val;
ptr->next = NULL;
if(add_to_end)
{
curr->next = ptr;
curr = ptr;
}
else
{
ptr->next = head;
head = ptr;
}
return ptr;
}
struct test_struct* search_in_list(int val, struct test_struct **prev)
{
struct test_struct *ptr = head;
struct test_struct *tmp = NULL;
bool found = false;
printf("\n Searching the list for value [%d] \n",val);
while(ptr != NULL)
{
if(ptr->val == val)
{
found = true;
break;
}
else
{
tmp = ptr;
ptr = ptr->next;
}
}
if(true == found)
{
if(prev)
*prev = tmp;
return ptr;
}
else
{
return NULL;
}
}
int delete_from_list(int val)
{
struct test_struct *prev = NULL;
struct test_struct *del = NULL;
printf("\n Deleting value [%d] from list\n",val);
del = search_in_list(val,&prev);
if(del == NULL)
{
return -1;
}
else
{
if(prev != NULL)
prev->next = del->next;
if(del == curr)
{
curr = prev;
}
else if(del == head)
{
head = del->next;
}
}
free(del);
del = NULL;
return 0;
}
void print_list(void)
{
struct test_struct *ptr = head;
printf("\n -------Printing list Start------- \n");
while(ptr != NULL)
{
printf("\n [%d] \n",ptr->val);
ptr = ptr->next;
}
printf("\n -------Printing list End------- \n");
return;
}
int main(void)
{
int i = 0, ret = 0;
struct test_struct *ptr = NULL;
print_list();
for(i = 5; i<10; i++)
add_to_list(i,true);
print_list();
for(i = 4; i>0; i--)
add_to_list(i,false);
print_list();
for(i = 1; i<10; i += 4)
{
ptr = search_in_list(i, NULL);
if(NULL == ptr)
{
printf("\n Search [val = %d] failed, no such element found\n",i);
}
else
{
printf("\n Search passed [val = %d]\n",ptr->val);
}
print_list();
ret = delete_from_list(i);
if(ret != 0)
{
printf("\n delete [val = %d] failed, no such element found\n",i);
}
else
{
printf("\n delete [val = %d] passed \n",i);
}
print_list();
}
return 0;
}
Is there anyother way to add,delete and find nodes in a linked list without using #include<stdbool.h> ?
Yes, don't use any bool types in your code.

Implementation of Stacks using Linked List. Where am I going wrong?

This is the code I've written in C :
#include<stdio.h>
struct Node
{
int info;
struct Node *next;
};
void init_Node(struct Node *n)
{
n->next = NULL;
}
struct Node *front = NULL;
void display()
{
struct Node *rear = front;
if(rear == NULL)
printf("List is empty!\n");
else
{
printf("[%i]-->",rear->info);
rear = rear->next;
}
printf("NULL");
printf("\n");
}
void addEnd(int x)
{
struct Node *n = malloc(sizeof(struct Node));
struct Node *rear = front;
n->info = x;
if(front == NULL)
front = n;
else
{
while(rear->next != NULL)
rear = rear->next;
rear->next = n;
rear = n;
}
display();
}
void deleteEnd()
{
struct Node *rear = front;
if(front == NULL)
printf("Stack is Empty!");
else
{
while(rear->next->next != NULL)
{
rear = rear->next;
}
printf("Popped : %i\n", rear->next->info);
rear->next = NULL;
display();
}
}
int main()
{
struct Node *n = malloc(sizeof(struct Node));
init_Node(n);
clrscr();
addEnd(23);
addEnd(45);
addEnd(8);
addEnd(57);
deleteEnd();
addEnd(98);
deleteEnd();
getch();
return 0;
}
The below output is the output when the implementation was done in C++ using classes.
The output for the program was supposed to be this -
but the output of my code is this -
EDIT
After adding the while() loop and adding n->next = NULL; the output comes out to be :
Where am I going wrong?
You need two changes:
void display()
{
struct Node *rear = front;
if(rear == NULL)
printf("List is empty!\n");
else
{
// CHANGE 1: You need a while loop here
while(rear != NULL) {
printf("[%i]-->",rear->info);
rear = rear->next;
}
}
printf("NULL");
printf("\n");
}
void addEnd(int x)
{
struct Node *n = malloc(sizeof(struct Node));
struct Node *rear = front;
n->info = x;
// CHANGE 2: You need to clear n->next to NULL.
n->next = NULL;
if(front == NULL)
front = n;
else
{
while(rear->next != NULL)
rear = rear->next;
rear->next = n;
rear = n;
}
display();
}
in your function, addEnd() you need to initialize the next pointer to zero. So, right after the line n->info = x; add a line n->next = 0;

Resources