Why does the node not inserted at the end? - c

After I compile the code, there is no output at all.
Why is the value 10 not inserted at the end of the linked list?
I thought that after p == NULL, the while loop is exited, j->next would be NULL as well. So, the temp node will be inserted at the end of the linked list.
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node *next;
}*first=NULL;
void Create(int array[], int size)
{
int i;
struct Node *temp, *last;
first = (struct Node*)malloc(sizeof(struct Node));
first->data = array[0];
first->next = NULL;
last = first;
for (i = 1 ; i < size ; i++){
temp = (struct Node*)malloc(sizeof(struct Node));
temp->data = array[i];
temp->next = NULL;
last->next = temp;
last = temp;
}
}
void Print(struct Node *p)
{
while(p != NULL){
printf("%d ", p->data);
p = p->next;
}
}
void InsertingInSortedList(struct Node *p, int value)
{
struct Node *temp , *j = NULL;
temp = (struct Node*)malloc(sizeof(struct Node));
temp->data = value ;
temp->next = NULL;
if(p == NULL){
first = temp;
}
else
{
while(p->data < value && p){
j = p;
p = p->next;
}
temp->next = j->next;
j->next = temp;
}
}
int main (void)
{
int b[] = {1,3,5,7,8,9};
int num = 6;
Create(b,num);
InsertingInSortedList(first, 10);
Print(first);
return 0;
}

The condition p->data < value && p is wrong. You need to check if p is NULL before you dereference p.
The correct condition is p && p->data < value.
Google c short circuit evaluation for more information.

Related

Unable to create and display linked list in C

I want to create integer linked list and display. Suppose there are 3 nodes with values 11,22,33 . But when I display it, its printing only 1st value i.e. 11 . What is going wrong?
NOTE : To create and display linked list , Whether head and p node variable are enough or is it must to take 3 node pointer variables . i.e. head , p and q also?
#include <stdio.h>
#include<stdlib.h>
typedef struct node
{
int data;
struct node *next;
}node;
int main()
{
int i, j, num, value;
node *p = NULL;
node *head = NULL;
printf("how many nodes\r\n");
scanf("%d",&num);
for(i = 0 ;i < num ; i++)
{
printf("enter node %d = ",i+1);
scanf("%d",&value);
p = (node *)malloc(sizeof(node));
p->data = value;
p->next = NULL;
if(head == NULL)
{
head = p;
}
}
printf("linked list formed is \r\n");
for(p = head ; p != NULL ; p = p->next)
{
printf("p->data = %d\r\n ",p->data);
}
return 0;
}
You build a forward-chained linked list in input order by constantly updating a target point on which to hang the next node.
Initially that pointer is the head pointer.
The next node will be hung on the next pointer of that previous node.
When done, the last next pointer is set to NULL and you're finished.
It may sound complicated, but utilizing a pointer-to-pointer makes the algorithm surprisingly simple, efficient, and requires no special tedious case for testing for a null head pointer that will only ever be true once. Including added error checking
#include <stdio.h>
#include <stdlib.h>
typedef struct node
{
int data;
struct node *next;
} node;
int main()
{
node *head = NULL;
node **pp = &head;
int num;
printf("how many nodes\r\n");
if (scanf("%d", &num) == 1 && num > 0)
{
for (int i=0; i<num;)
{
int value;
printf("enter node %d = ", i+1);
if (scanf("%d", &value) == 1)
{
*pp = malloc(sizeof **pp);
if (*pp == NULL)
{
perror("Failed to allocate new list node");
exit(EXIT_FAILURE);
}
// hang the new node
(*pp)->data = value;
// setup pp to hold address of next pointer
// to populate on the next iteration.
pp = &(*pp)->next;
// next node
++i;
}
else
{
int c;
while ((c = fgetc(stdin)) != EOF && c != '\n');
}
}
// terminate the list
*pp = NULL;
}
printf("linked list formed is:\n");
for (const node *p = head; p != NULL; p = p->next)
{
printf(" p->data = %d\n", p->data);
}
// free the list
while (head)
{
node *p = head;
head = head->next;
free(p);
}
return 0;
}
Sample Run
how many nodes
5
enter node 1 = 1
enter node 2 = 3
enter node 3 = 5
enter node 4 = 7
enter node 5 = 9
linked list formed is:
p->data = 1
p->data = 3
p->data = 5
p->data = 7
p->data = 9
You are just updating the head first time and not creating any links
please find the fixed code below
#include <stdio.h>
#include<stdlib.h>
typedef struct node
{
int data;
struct node *next;
}node;
int main()
{
int i, j, num, value;
node *p = NULL;
node *head = NULL;
printf("how many nodes\r\n");
scanf("%d",&num);
for(i = 0 ;i < num ; i++)
{
printf("enter node %d = ",i+1);
scanf("%d",&value);
p = (node *)malloc(sizeof(node));
p->data = value;
p->next = NULL;
// Form links
p->next = head;
head = p;
}
printf("linked list formed is \n");
for(p = head ; p != NULL ; p = p->next)
{
printf("%d ",p->data);
}
printf("\n");
// Freeing memory to avoid mem leaks
for(p = head ; head != NULL ; head = head->next)
{
p = head;
free(p);
}
return 0;
}
You can refer to my library for a more generic implementation of link_list
A change in code by Mohammed Meraj to create the list in the correct order.
#include <stdio.h>
#include <stdlib.h>
typedef struct node{
int data;
struct node *next;
}node;
int main()
{
int i, num, value;
node *p = NULL;
node *head = NULL;
node *q = NULL;
printf("how many nodes\r\n");
scanf("%d",&num);
for(i = 0 ;i < num ; i++)
{
printf("enter node %d = ",i+1);
scanf("%d",&value);
p = (node *)malloc(sizeof(node));
p->data = value;
p->next = NULL;
// Form links
if(!q) head = q = p;
else{ q->next = p; q = p; }
}
printf("linked list formed is \n");
for(p = head ; p != NULL ; p = p->next)
{
printf("%d ",p->data);
}
printf("\n");
// Freeing memory to avoid mem leaks
while(head != NULL)
{
p = head;
head = head->next;
free(p);
}
return 0;
}
if you want to do the code with only head and p, it can be done too
#include <stdio.h>
#include <stdlib.h>
typedef struct node{
int data;
struct node *next;
}node;
int main()
{
int i, num, value;
node *p = NULL;
node *head = NULL;
printf("how many nodes\r\n");
scanf("%d",&num);
for(i = 0 ;i < num ; i++)
{
printf("enter node %d = ",i+1);
scanf("%d",&value);
if(!head){
head = (node *)malloc(sizeof(node));
head->data = value;
head->next = NULL;
p = head;
}else{
p->next = (node *)malloc(sizeof(node));
p->next->data = value;
p->next->next = NULL;
p = p->next;
}
}
printf("linked list formed is \n");
for(p = head ; p != NULL ; p = p->next)
{
printf("%d ",p->data);
}
printf("\n");
// Freeing memory to avoid mem leaks
while(head != NULL)
{
p = head;
head = head->next;
free(p);
}
return 0;
}

linked list program is not functioning properly

The given program is not showing all the elements of the linked list.
I am having problem in identifying the error.
At first I initialized the head with a null value then made a temporary variable and assigned it an integer value and pointer to the next node.
Then I made an another node named temp1 and linked it with the head.
It will only be linked when "i" will be equal to 1.
Then equated temp1 to the next node and did the same.
//Linked list
//Inserting the nodes.
#include <stdio.h>
struct node
{
int n;
struct node *next;
};
struct node *head;
int main ()
{
int i, s, x, y;
i = 0;
struct node *temp;
struct node *temp1;
struct node *cur;
head = NULL;
scanf ("%d", &s); //No. of nodes.
while (i < s)
{
scanf ("%d", &x);
if (head == NULL)
{
temp = (struct node *) malloc (sizeof (struct node));
temp->n = x;
temp->next = NULL;
head = temp;
}
else
{
temp = (struct node *) malloc (sizeof (struct node));
temp->n = x;
temp->next = NULL;
temp1 = temp;
if (i == 1)
{
head->next = temp1;
}
temp1 = temp1->next; //Assigning the next node.i.e. NULL value
}
i = i + 1;
}
cur = head;
while (cur != NULL)
{
printf ("%d", cur->n);
cur = cur->next;
}
return 0;
}
Check the following changed section
{
temp = (struct node *) malloc (sizeof (struct node));
temp->n = x;
temp->next = NULL;
head = temp;
temp1 = head;
}
else
{
temp = (struct node *) malloc (sizeof (struct node));
temp->n = x;
temp->next = NULL;
temp1->next = temp;
temp1 = temp1->next; //Assigning the next node.i.e. NULL value
}
Instead of relying on
if (i == 1) {
head->next = temp1;
}
I assign head on temp1 while creating the head, which is meant to be happen only first time.
There were also some linkage issues in your else portion.
You lose nodes beyond the first two, since you never link them to the list. Use meaningful names for variables: rename temp1 to tail and initialize it to NULL in the beginning. Then the loop body becomes:
if (scanf(" %d", &x) != 1) {
// FIXME: handle error
}
temp = malloc(sizeof(*temp));
temp->n = x;
temp->next = NULL;
if (tail == NULL) {
head = temp;
} else {
tail->next = temp;
}
tail = temp;
++i;
(Untested.)
Rationale: You want to add new nodes to the end (tail) of the list. The easiest way is to keep track of the tail in an appropriately-named variable, and simply link every node to tail->next instead of convoluted logic like checking for the node count, etc. The only special case is the empty list, i.e., both head and tail are NULL, and the difference is just one line, so don't duplicate the whole block of code to set up the new node.
For starters you have to include the header <stdlib.h>.
The problem is in this statement
temp1 = temp;
if i is not equal to 1 then after this statement
temp1 = temp1->next;
temp1 becomes equal to NULL.
So all other nodes are not added to the list because there is a cycling
temp1 = temp;
//...
temp1 = temp1->next;
Change the loop the following way
while (i < s)
{
scanf ("%d", &x);
if (head == NULL)
{
temp = (struct node *) malloc (sizeof (struct node));
temp->n = x;
temp->next = NULL;
head = temp;
temp1 = head;
}
else
{
temp = (struct node *) malloc (sizeof (struct node));
temp->n = x;
temp->next = NULL;
temp1->next = temp;
temp1 = temp;
}
i++;
}
Pay attention to that you should declare variables in a block scope where they are used. Otherwise the program will be unreadable.
The approach you are using can be called as an Java approach.
In C the program can look much simpler. For example
#include <stdio.h>
#include <stdlib.h>
struct node
{
int n;
struct node *next;
};
struct node *head;
int main( void )
{
struct node **temp = &head;
size_t n = 0;
scanf( "%zu", &n );
for ( size_t i = 0; i < n; i++ )
{
*temp = (struct node *) malloc ( sizeof ( struct node ) );
int value = 0;
scanf ( "%d", &value);
( *temp )->n = value;
( *temp )->next = NULL;
temp = &( *temp )->next;
}
for ( struct node *cur = head; cur != NULL; cur = cur->next )
{
printf ("%d -> ", cur->n );
}
puts( "NULL" );
return 0;
}
Its output might look like
1 -> 2 -> 3 -> NULL

struct undeclared (first use in this function)

I'm very new to programming and I started to learn C. Now I just cant understand why my node structure is not visible to my functions.
I try to get some help on http://www.cprogramming.com/tutorial/c/lesson7.html
but with no luck in using code blocks 13.12
#include <stdio.h>
#include <stdlib.h>
struct node {
int data;
struct ptr * next;
};
struct node* head;
void Insert(int x)
{
struct node *temp;
temp = (node*)malloc(sizeof(struct node));
if(head == NULL)
head = temp;
temp->data = x;
temp->data = x;
temp->next = NULL;
struct node* temp1 = head;
while(temp1-> != NULL;) {
temp1 = temp1->next;
}
temp1->next = temp;
}
void print() {
struct node* temp = head;
while(temp != NULL) {
printf("the data is %d", temp->data);
temp = temp->next;
}
}
int main ()
{
head = NULL;
int a,c;
printf("How many numbers ? : \n");
scanf("%d",&a);
for(i = 0; i<a; i++); {
printf("Enter a number:\n");
scanf("%d",&c);
Insert(c);
print();
}
}
There are quite a few lets go one by one
number 1
struct node {
int data;
struct node *next; // chagnge ptr -> node
};
number 2
struct node *temp;
temp = malloc(sizeof(struct node)); // struct node casting
number 3
while(temp1->next != NULL) { // remove semi colum and put a next
temp1 = temp1->next;
}
number 4
int i; // for while loop
for(i = 0; i<a; i++) {
Now hopefully it compiles well, check runtime errors ( if any )
and yes
return 0; // just before main
you are building an infinite loop with your first element:
temp = (struct node*)malloc(sizeof(struct node));
if(head == NULL)
head = temp;
temp->data = x;
temp->next = NULL;
struct node* temp1 = head;
while(temp1->next != NULL) { // nothing to do
temp1 = temp1->next;
}
temp1->next = temp; //temp is head and temp1 is head, so head->next points to head
you should do something like
if (head == NULL) {
//fill head and leave
} else {
//traverse to the last element and concatenate the new element
}

Error while finding max and min in a circular linked list

I need to find the maximum number and the minimum number in a circular linked list and i should move the minimum number to the start of the list (before head) and the maximum number to the end of the list (before minimum)
why my code is giving me error in output?
Note: Using doubly linked list is disallowed ,we should do this only with circular linked list.
#include <stdio.h>
#include <stdlib.h>
typedef struct node
{
int num;
struct node *next;
} NODE;
void init(NODE **h)
{
(*h) = (NODE*)malloc(sizeof(NODE));
(*h)->next = *h;
}
NODE* add(NODE* h,NODE* p,int x)
{
int i;
NODE *temp;
temp = (NODE*)malloc(sizeof(NODE));
temp->num = x;
temp->next = h;
if(h->next == h)
{
h->next = temp;
return h;
}
else
{
temp = p->next;
p = temp;
return h;
}
return h;
}
NODE* fin(NODE *h,NODE *p)
{
NODE* ptr,*pmin,*pmax,*temp,*temp2,*mnprev,*mxprev;
// temp: minimum
// temp2: maximum
// pmin: holds the minimum
// pmax: holds the maximum
// ptr: o(n) search
// mnprev: holds the previous node of the minimum
// mxprev: hold the previous node of the maximum
mnprev = mxprev = pmin = pmax = h;
ptr = h->next;
int mini, maxi;
mini = h->num;
maxi = h->num;
do
{
if(ptr->num < mini)
{
mini = ptr->num;
pmin = ptr;
mnprev->next = pmin;
}
if(ptr->num > maxi)
{
maxi = ptr->num;
pmax = ptr;
mxprev->next = pmax;
}
ptr = ptr->next;
} while(ptr != h);
temp = pmin;
temp2 = pmax;
mnprev->next = pmin->next;
mxprev->next = pmax->next;
free(pmin);
free(pmax);
temp->next = h;
temp2->next = temp;
ptr = temp;
do {
printf("%d ",ptr->num);
ptr = ptr->next;
} while(ptr != h);
}
int main()
{
int i,x;
NODE *lis,*p;
init(&lis);
p = lis;
for(i=0;i<7;i++)
{
scanf("%d",&x);
add(lis,p,x);
}
fin(lis,p);
}
rewrite your code
function init delete as it will create nodes that are not used.
Changed to the node between the maximum and minimum values ​​since it
is sufficient to simply replace the value.
like this
#include <stdio.h>
#include <stdlib.h>
typedef struct node {
int num;
struct node *next;
} NODE;
NODE* add(NODE **head, NODE **tail, int x){
NODE *temp;
temp = (NODE*)malloc(sizeof(NODE));
temp->num = x;
if(*head == NULL){
temp->next = temp;
*tail = *head = temp;
} else {
temp->next = *head;
(*tail)->next = temp;
*tail = temp;
}
return *head;
}
void print(NODE *p){
NODE *top =p;
do{
printf("%d ", p->num);
p=p->next;
}while(p != top);
printf("\n");
}
void drop(NODE *head, NODE *tail){
NODE *p = head;
tail->next = NULL;
while(p){
NODE *temp = p;
p = p->next;
free(temp);
}
}
void minmax(NODE *head, NODE *tail){
NODE *p, *maxp, *minp;
int temp;
maxp = minp = p = head;
do{
if(maxp->num < p->num){
maxp = p;
}
if(minp->num > p->num){
minp = p;
}
p = p->next;
}while(p != head);
temp = maxp->num; maxp->num = tail->num; tail->num = temp;
if(tail == minp)//exchanged minp
minp = maxp;//fixed
temp = minp->num; minp->num = head->num; head->num = temp;
}
int main(void){
int i, x;
NODE *head, *tail;
tail = head = NULL;
for(i=0;i<7;i++){
printf("%d>", i+1);
scanf("%d", &x);
add(&head, &tail, x);
}
//print(head);
minmax(head, tail);
print(head);
drop(head, tail);
return 0;
}

why is this print linked list function not working?

I have a function as following
void printLinkedList(struct node *head) {
printf("%d-->", head->data);
while(head->ptr != NULL) {
head = head->ptr;
printf("%d-->", head->data);
}
printf("NULL\n");
}
I would like to print the content of a linked list constructed in the following way:
for (int i = 0; i < 10; i++) {
head->data = i+1;
head->ptr = malloc(sizeof(struct node));
head = head->ptr;
}
So ideally this should give me something like:
1-->2-->3-->4-->...-->10-->NULL
If everything is correct, however, valgrind is giving me memory errors. Please tell me what I am doing wrong.
check this.
struct node *temp, *head= NULL, *last = NULL;
for (int i = 0; i < 10; i++) {
temp = malloc(sizeof(struct node));
temp->data = i+1;
temp->ptr = NULL;
if (head == NULL)
head = temp;
if (last != NULL)
last->ptr = temp;
last = temp;
}
printLinkedList(head);
I revised Toms's answer a little:
struct node *head = NULL, **temp = &head;
for (int i = 0; i < 10; i++) {
*temp = malloc(sizeof(struct node));
(*temp)->data = i+1;
(*temp)->ptr = NULL;
temp = &(*temp)->ptr;
}
printLinkedList(head);
The orignal code produces a seg fault because temp is not malloced properly.
If you call print function without constructing the Linked list, it will show error, so change the print function as follows:
void printLinkedList(struct node *head)
{
while(head != NULL)
{
printf("%d-->", head->data);
head = head->ptr;
}
printf("NULL\n");
}
here is the revised code - your construction was faulty.
typedef struct _node {
int data;
struct _node *ptr;
} NODE, *PNODE;
PNODE head;
int main (int argc, char * argv[])
{
head = (PNODE) malloc(sizeof(NODE));
PNODE node = head;
int i = 0;
node->data = ++i;
node->ptr = NULL;
for ( ;i < 10; ) {
PNODE tmp = (PNODE) malloc(sizeof(NODE));
tmp->data = ++i;
tmp->ptr = NULL;
node->ptr = tmp;
node =tmp;
}
printLinkedList(head);
freeLinkedList(head);
return 0;
}

Resources