Program to create a linked list not working - c

Only the head element gets printed and no element gets printed further.
My guess is that the code inside else{.....} inside the createLinkedList(int n) function portion isn't seem to be doing it's job.
Code is below :
#include <stdio.h>
#include <stdlib.h>
struct Node
{
int data;
struct Node * next;
}*head;
void createLinkedList(int n)
{
int i;
struct Node *temp, *p;
for(i=1; i<=n; i++)
{
// First thing we do is create an ISOLATED NODE WHICH IS NOT LINKED TO ANYTHING
temp = (struct Node *)malloc(sizeof(struct Node));
printf("Now enter your element %d of linked list: ",i);
scanf("%d",&(temp->data));
temp->next = NULL;
// ISOLATED NODE CREATED. SINCE THIS IS UNLINKED, WE MUST STORE IT'S POINTER VARIABLE TO NULL
if(head == NULL) // Meaning our Linked List is empty
head = temp;
else // Meaning our Linked List is not empty. Has at least one element.
{
p = head;
while(p != NULL)
p = p->next; // Accessing Last pointer of Linked List
p = temp; // THAT IOSOLATED NODE Is Hereby Connected to our final Linked LIST Element
}
printf("\n");
}
}
int main()
{
head = NULL;
printf("Enter the length of your linked list: ");
int n;
scanf("%d", &n);
printf("\n");
createLinkedList(n);
return 0;
}

Change while(p != NULL) p = p->next;
to
while(p->next != NULL)
p = p->next;
That would give you the last pointer position where you can insert your node. Right now, p will be null at the end of the iteration.
After that you need to do p->next = temp so that your newly created node is added to the linked list.

Instead of looping in else block, we can track the tail pointer for last node in linked list. Below is modified code:
void createLinkedList(int n)
{
int i;
struct Node *temp, *tail;
for(i=1; i<=n; i++)
{
// First thing we do is create an ISOLATED NODE WHICH IS NOT LINKED TO ANYTHING
temp = (struct Node *)malloc(sizeof(struct Node));
printf("Now enter your element %d of linked list: ",i);
scanf("%d",&(temp->data));
temp->next = NULL;
// ISOLATED NODE CREATED. SINCE THIS IS UNLINKED, WE MUST STORE IT'S POINTER VARIABLE TO NULL
if(head == NULL) // Meaning our Linked List is empty
{
head = temp;
tail = temp;
}
else // Meaning our Linked List is not empty. Has at least one element.
{
tail->next = temp; // THAT IOSOLATED NODE Is Hereby Connected to our final Linked LIST Element
tail = temp;
}
printf("\n");
}
}
int main()
{
head = NULL;
printf("Enter the length of your linked list: ");
int n;
scanf("%d", &n);
printf("\n");
createLinkedList(n);
return 0;
}

your code working but you lose the addresses of the next nodes when you are using while(p != NULL) so you should change it to while(p->next != NULL){p=p->next;}{p->next=temp;}.

Related

How to build a Linked_list_builder function in C

I am learning about linked list, I want to make a function which creates a linked list, after that I want to make a for loop which will print our linked list at main function.
I tried this:
#include <stdio.h>
#include <stdlib.h>
typedef struct linked_list {
int data;
struct linked_list* link;
}node;
//building list
node linked_list_builder(int length) {
node* list;
list = (node*) malloc(length * sizeof(node));
for(int i=0;i<length;i++)
{
printf("Data in list no.%d at index %d = ",i+1,i);
scanf("%d",list->data);
list->link += 1;
}
return *list;
}
int main() {
int length;
printf("Enter the length of Linked list:\n");
scanf("%d", &length);
node list = linked_list_builder(length);
//printing list
for(int i=0;i<length;i++)
{
printf("index %d->list %d = %d\n",i,i+1,list.data);
list.link++;
}
return 0
}
I don't know what's the exact problem, I don't know how can I return my linked list from function, and How can I actually travel it and print its data?
You have two problems:
As pointed out by #WhozCraig:
You are reserving space for all nodes at once, if that were possible, you would have no need to create a list (with its handicap of memory fragmentation and also needing an extra pointer to point to the next node) and in that case it would be enough to use an array.
A list is useful when you don't know the number of elements you need beforehand. If you really need a list, store the position of the first element of the list in a variable (head) and add elements to that list one by one through a push function:
node *linked_list_push(node *tail, int data) {
node *curr = calloc(1, sizeof(node));
curr->data = data;
if (tail != NULL) {
tail->link = curr;
}
return curr;
}
node *head = NULL, *tail = NULL;
// pushing list
for (int i = 0; i < length; i++) {
tail = linked_list_push(tail, i);
if (head == NULL) {
head = tail;
}
}
// printing list
while (head) {
node *temp = head;
printf("%d\n", head->data);
head = head->link;
free(temp);
}
And as pointed out by #Kuro:
scanf wants a pointer:
scanf("%d",list->data);
should be
scanf("%d",&list->data);

How to print all the nodes in a circular linked list in C

I'm trying to implement a circular linked list in C, however I cant seem to print the nodes one by one. Below is the code for assigning the values and then printing them. Whenever I run it, all it prints out is "NULL". I would like to know what should i do so that it prints out "1 -> 2 -> 3 -> ...."
void tail_insert(struct Node * head, struct Node * tail, int num){
struct Node * p = (struct Node*) malloc(sizeof(struct Node));
p->info = num;
p->next = head;
if (head == NULL) {
head = p;
tail = head ;
}
else{
tail->next = p;
tail = p;
}
}
void print_list(struct Node * head)
{
struct Node * current = head;
while (current != NULL)
{
printf("%d -> ", current->info);
current = current->next;
}
printf("NULL\n");
}
int main(){
struct Node * head = NULL, * tail = NULL;
int num = 0;
int length;
int deletespace;
scanf("%d %d", &length, &deletespace);
for (int i = 1; i < length+1 ; i++){
tail_insert(head, tail, i);
}
print_list(head);
The reason you're not getting nodes printed is because of how pass by value works. When you call tail_insert, you're passing a basic pointer. Dereferencing and modifying this inside the function would modify the values pointed to by head and tail, but not carry changes to the pointers themselves outside the function.
One way of fixing this is to change the head and tail parameters to be pointers to pointers (**) and passing the addresses of those variables where you call the function in main.

try to find middel but program crash linked list in c with two pointers

i write function whom Traverse linked list using two pointers. Move one pointer by one and other pointer by two. When the fast pointer reaches end slow pointer will reach middle of the linked list.
but my code crash when i try to move temp pointer by two
#include <stdio.h>
#include <stdlib.h>
#define MEM (struct node*) malloc(sizeof(struct node))
void addl(); //add elements at last
void print(); //print linked list
void addf(); //add element at first
void addm(); //add element at middel
struct node {
int data;
struct node* next;
};
struct node* head;
void addl()
{
struct node* new, *temp;
temp = head;
new = MEM;
printf("\n\t\tenter any number : ");
scanf("%d", &new->data);
new->next = 0;
if (temp == 0)
head = new;
else {
while ((temp->next != 0))
temp = temp->next;
temp->next = new;
}
}
void print()
{
struct node* temp = head; //
printf(" \n Elements are : ");
while (temp != 0) {
printf(" %d ", temp->data);
temp = temp->next;
}
}
void addf()
{
struct node* new;
new = MEM;
printf("\n\t\tenter any number : ");
scanf("%d", &new->data);
new->next = head;
head = new;
}
void addm()
{
struct node* new, *temp, *med;
temp = head;
med = head;
new = MEM; //MEM #define for dynamic memory allocation
printf("\n\t\tenter m any number : ");
scanf("%d", &new->data);
if (temp == 0)
head = new;
else {
while ((temp = temp->next != 0)) {
med = med->next;
temp = temp->next; //fist move
temp = temp->next; //2nd move when i add program crash
}
// new->next=med;
//med->next=new;
printf("\n\t\tDATA : %d\n", med->data);
}
}
int main()
{
head = 0;
int i = 5; //create linked list
while (i) {
system("cls");
addf();
addl();
i--;
}
addm();
print();
return 0;
}
as of now addm not add anything in linked list because code crash while i try to found mid of linked list
The crash is due to these two line -
temp=temp->next;//for one move
temp=temp->next;//for second move when i add this program crash
Let's think of two situations -
1) List has one element. Then after the while check condition, dur to temp=temp->next line temp will point to NULL. In next temp=temp->next line you are trying to de-reference that NULL. That will crash
2) List have 2 elements. After while condition check temp will point to last element. And after next temp=temp->next line temp will point to NULL. Now in very next line you are trying to de-reference that NULL. Which is another point of crash
You need to remove one temp=temp->next from inside loop as it advances temp by 3 position in each loop iteration which is clearly a logical bug. Node that after that removing one of them will not eliminate the chance of crash.
Another thing is that the commented code is also wrong.
// new->next=med;
//med->next=new;
You may have wanted to do -
new->next = med->next;
med->next = new;

How do you get a data section from a Linked list to compare?

I have just started learning linked list and was messing around with it but then I ran into a problem. I was not sure how to access the data member to actually compare it. In my code, I prompt the user to input grades and when they input -1 then it signals that they are finished. My first thought was to get the pointer pointing to the node to get the data like I did in scanf, however I can't compare pointers to integers. Is there a way to get data members from linked lists to compare? Also, pointing out other errors would be appreciated as well because I don't know linked lists too well. I have the following code:
int main() {
struct Node
{
int grade;
struct Node *next;
};
struct Node *head;
struct Node *first;
struct Node *temp = 0;
first = 0;
while (****** != -1) { //This is what I need the data from linked list for
head = (struct Node*)malloc(sizeof(struct Node));
printf("Enter the grade: \n ");
scanf("%d", &head -> grade);
if (first != 0) {
temp -> next = head;
temp = head;
}
else
{
first = temp = head;
}
}
}
There is a number of issue with your code:
1) Don't scan directly into the list - use a temp variable
2) Always check return values
3) Make sure to initialize variables, i.e. head
Try something like:
struct Node
{
int grade;
struct Node *next;
};
int main() {
struct Node *head = NULL;
struct Node *temp;
int data;
while (1)
{
printf("Enter the grade: \n ");
if (scanf("%d", &data) != 1)
{
// Illegal input
exit(1);
}
if (data == -1) break; // Stop the loop
temp = malloc(sizeof *temp); // Allocate new element
if (temp == NULL)
{
// Out of mem
exit(1);
}
temp -> next = head; // Insert new element in the front of list
temp -> grade = data;
head = temp; // Move the front (aka head) to the new element
}
// .... add code that uses the list
return 0;
}

Program is Inserting node after first element in circular linklist why?

i am trying to write a simple circular link list program where i want to insert node at the start.
1: first i created list.
2: then i want to insert element at beginning.
when i am trying to output its displaying the element is inserted after first element, which i am not expecting .
i tried a lot of post if someone face the same issue but no fruitful results.
can some one help me in this ..
#include<stdio.h>
#include<stdlib.h>
typedef struct llist
{
int data;
struct llist *next;
}list;
void createlist(list**, int);
void InsertAtbeg(list**, int);
void display(list*);
int main()
{
list *node = NULL;
int i,n;
printf("\n enter no of elements:-");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
createlist(&node, i);
}
display(node);
InsertAtbeg(&node, 100);
printf("\n elements after insertion at beg :-");
display(node);
return 0;
}
void createlist(list **H, int x)
{
list *p,*r;
if(*H==NULL)
{
p = (list*)malloc(sizeof(list));
p->data =x;
p->next = p;
*H = p;
}
else
{
r = (list*)malloc(sizeof(list));
r ->data =x;
p->next =r;
r->next =*H;
p=r;
}
}
void InsertAtbeg(list**H, int x)
{
list* p,*r;
r=*H;
p= (list*)malloc(sizeof(list));
p->data =x;
p->next = r->next;
r->next = p;
*H=r;
}
void display(list* H)
{
list *p;
if(H!=NULL)
{
p = H;
while (p->next != H)
{
printf("\n elements in list are:- %d", p->data);
p = p->next;
}
printf("\n elements in list are:- %d", p->data);
}
}
You will have make the InsertAtbeg to return the new node added and set it as the head and pass it to the display. Instead, what you are doing is passing the old head, which is clearly incorrect.
Add the required headers
#include<stdio.h>
#include<stdlib.h>
Your createlist is improper (I did not inspect it but wrote a quick for loop inside the main).
int main() {
list *head = malloc(sizeof(list));
list *node = head;
int i,n;
printf("\n enter no of elements: ");
scanf("%d",&n);
for (i=1;i<=n;i++) {
node->data = i;
if (i<n) {
node->next = malloc(sizeof(list));
node = node->next;
} if (i==n)
node->next = head;
}
display(head);
list* I = InsertAtbeg(node, 100);
printf("\n elements after insertion at beg :-");
display(I); // here you need to pass the new node "I" as head
return 0;
}
Now the InsertAtBeg you can actually pass the last node but not the head. You can get the head from the last->next and make it return the new head.
list* InsertAtbeg(list *Last, int x) {
list *Head = Last->next;
list *Insert = malloc(sizeof(list));
Last->next = Insert;
Insert->data = x;
Insert->next = Head;
return Insert;
}
The display function I left it as it is.
Below is a copy of your code. I've added comments to explain what is wrong.
void InsertAtbeg(list**H, int x)
{
list* p,*r;
r=*H;
p= (list*)malloc(sizeof(list));
p->data =x;
p->next = r->next; // wrong: must be p->next = r as the new element
// shall point to the current head
r->next = p; // wrong: delete this line - no need for changing
// next of current head
*H=r; // wrong: must be *H = p so the new element becomes head
// wrong: you are not done yet. you miss that the last element
// shall have its next pointer updated
// so that it points to the new element
}
BTW: Your createlist has undefined behavior as p is not initialized

Resources