Linked List not printing - c

I am trying to create a simple linked list using C, I think I was able to construct the linked list itself, but when I try and print it, it prints the value of the last node instead of all the values in the list.
#include <stdio.h>
#include <alloca.h>
typedef int DATA;
struct Node
{
DATA d;
struct Node *next;
};
void printList(struct Node **head)
{
struct Node *newNode = (struct Node *)malloc(sizeof(struct Node));
struct Node *temp;
temp = *head;
while(temp!=NULL)
{
printf("%d \n", temp->d);
temp = temp->next;
}
}
int main()
{
struct Node *newNode = (struct Node *)malloc(sizeof(struct Node));
struct Node *head = newNode;
struct Node *temp = newNode;
head->d = 1;
int i = 0;
printf("Enter 3 numbers");
for( i = 0; i< 3; i++)
{
scanf("%d", &temp->d);
temp->next = newNode;
temp = temp->next;
}
temp->next = NULL;
printf("%d \n", temp->d);
return 0;
}
Any help/tips would be greatly appreciated.

There are multiple problems in your code:
You are not creating the list properly. You are allocating memory for only one node and playing around with pointers improperly causing the linked list to be pointed to the same memory
You are not calling printList function at all
It is not clear why you are allocating memory again in printList whereas it should be printing the already created list
Also, no need to pass double pointer for printList as you are not modifying the list.
Though you should be understanding and doing the changes yourself, I am providing a below modified program which I hope will help you understand the mistakes in your code.
Please see the below modified version of the code
#include<stdio.h>
#include <alloca.h>
typedef int DATA;
struct Node
{
DATA d;
struct Node *next;
};
void printList(struct Node *head)
{
struct Node *temp = head;
while(temp!=NULL)
{
printf("%d \n", temp->d);
temp = temp->next;
}
}
struct Node *createNode()
{
struct Node *newNode;
newNode = malloc(sizeof(struct Node));
if (NULL == newNode)
return NULL;
memset(newNode, 0, sizeof(struct Node));
return newNode;
}
int main()
{
struct Node *newNode = NULL;
struct Node *headNode = NULL;
struct Node *temp = NULL;
int i = 0;
int data = 0;
printf("Enter 3 numbers\n");
for( i = 0; i< 3; i++)
{
scanf("%d", &data);
newNode = createNode();
if (NULL == newNode)
break;
newNode->d = data;
if (headNode == NULL)
{
headNode = newNode;
temp = newNode;
}
else
{
temp->next = newNode;
temp = temp->next;
}
}
printList(headNode);
return 0;
}

Replace your code with the following code :-
#include<stdio.h>
#include <alloca.h>
typedef int DATA;
struct Node
{
DATA d;
struct Node *next;
};
void printList(struct Node **head)
{
struct Node *newNode = (struct Node *)malloc(sizeof(struct Node));
struct Node *temp;
temp = *head;
while(temp->next!=NULL)
{
printf("%d \n", temp->d);
temp = temp->next;
}
}
int main()
{
struct Node *newNode = (struct Node *)malloc(sizeof(struct Node));
struct Node *head = newNode;
struct Node *temp = newNode;
head->d = 1;
int i = 0;
printf("Enter 3 numbers");
for( i = 0; i< 3; i++)
{
struct Node *newNode = (struct Node *)malloc(sizeof(struct Node));
scanf("%d", &temp->d);
temp->next = newNode;
temp = temp->next;
}
printList(head);
return 0;
}
Here you need to declare the newNode in the loop also while taking the input. As, the current value is over-writted, the old value is lossed and only the value of last node is printed.
Also while printing, check for temp->next!=Null instead of temp!=NULL

Related

Segmentation fault in linked list program (c language)

I'm trying to write a code for linked lists using c++. Insert at begin and Insert at end are not working for some reason. Here is the code.
`
#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
void insertAtBeginning(int );
void insertAtEnd(int );
void printLL();
struct Node
{
int data;
struct Node *link;
};
struct Node *head;
int main()
{
struct Node *temp, *newnode;
int ch=1, i=1, info;
head = NULL;
while(ch)
{
printf("Enter data: ");
scanf("%d", &info);
newnode = (struct Node *)malloc(sizeof(struct Node));
newnode->data = info;
newnode->link = NULL;
if(head == NULL)
{
head = newnode;
temp = newnode;
}
else
{
temp ->link = newnode;
temp = newnode;
}
printf("You wish to continue? (press 0 to terminate)\n");
scanf("%d",&ch);
if(!ch)
{
break;
}
}
temp = head;
while(temp!=NULL)
{
printf("%d -> ",temp->data);
temp = temp->link;
}
printf("\n");
insertAtBeginning(50);
insertAtEnd(150);
//printLL();
}
void insertAtBeginning(int info)
{
struct Node *newnode;
newnode->data = info;
printf("\n%d\n", newnode ->data);
newnode->link = head;
head = newnode;
}
void insertAtEnd(int info)
{
struct Node *temp, *newnode;
newnode->link = NULL;
newnode->data = info;
temp = head;
while(temp!=NULL)
{
temp = temp->link;
}
temp->link = newnode;
printf("\n%d\n", newnode -> data);
}
void printLL()
{
struct Node *temp;
temp = head;
while(temp!=NULL)
{
printf("%d -> ",temp->data);
temp = temp->link;
}
}
`
The problem is somewhere around newnode->data = info in the functions.
I created two functions, one to insert an element at beginning and one to insert an element at end. In both of them, i've created a newnode. The problem is I cannot insert data into those nodes.
When you want to append a new node to the end of a linked list, you must find your last node (a node which its link is NULL, not itself). Also, it is better to use meaningful variable name (temp is too general name). You also forgot to malloc new nodes in insertAtBeginning and insertAtEnd functions. I've fixed these issues in the following code
#include<stdio.h>
#include<stdlib.h>
void insertAtBeginning(int );
void insertAtEnd(int );
void printLL();
struct Node
{
int data;
struct Node *link;
};
struct Node *head = NULL;
int main()
{
struct Node *it, *newnode, *tail;
int ch=1, i=1, info;
while(ch){
printf("Enter data: ");
scanf("%d", &info);
newnode = malloc(sizeof(struct Node));
newnode->data = info;
newnode->link = NULL;
if (head == NULL) {
head = newnode;
tail = newnode;
} else {
tail->link = newnode;
tail = newnode;
}
printf("You wish to continue? (press 0 to terminate, else to continue)\n");
scanf("%d",&ch);
if(ch == 0) {
break;
}
}
it = head;
while(it != NULL) {
printf("%d -> ",it->data);
it = it->link;
}
printf("\n");
insertAtBeginning(50);
insertAtEnd(150);
}
void insertAtBeginning(int info)
{
struct Node *newnode;
newnode = malloc(sizeof(struct Node));
newnode->data = info;
printf("\n%d\n", newnode->data);
newnode->link = head;
head = newnode;
}
void insertAtEnd(int info)
{
struct Node *it, *newnode;
newnode = malloc(sizeof(struct Node));
newnode->link = NULL;
newnode->data = info;
it = head;
while(it->link != NULL)
{
it = it->link;
}
it->link = newnode;
printf("\n%d\n", newnode->data);
}
void printLL()
{
struct Node *it;
it = head;
while(it!=NULL)
{
printf("%d -> ",it->data);
it = it->link;
}
}
You're treating your uninitialized stack variable (struct Node *newnode) as a pointer to a struct Node and trying to update its fields:
struct Node *newnode;
newnode->data = info;
This doesn't work because the value of newnode is whatever garbage was on the stack beforehand, and trying to deref it (*newnode) will likely give a seg fault since you're trying to read from some unknown memory address.
Notice how inside main, you assign a result from malloc to newnode, this means you know that (given that malloc didn't return NULL), the pointer is valid, and you're free to use the memory it points to.

Error: in creation of Linked List Display function

I am trying to create a linked list with display() function in it but i continuously getting error in it. a function not able to display element in output.
I have try various online solution of code but not worked on my code.
Below is my code if anyone have any idea. let me tell to solve it
#include <stdio.h>
#include <stdlib.h>
struct node{
int data;
struct node *next;
};
int create(int n){
int d1,d2,i;
struct node *head, *temp, *newnode;
head = (struct node *) malloc(sizeof(struct node));
printf("enter the data for node 1");
scanf("%d",&d1);
head->data = d1;
head->next = NULL;
temp = head;
for(i=2; i<=n; i++){
newnode = (struct node *)malloc(sizeof(struct node));
printf("enter a data for %d node",i);
scanf("%d",&d2);
newnode->data = d2;
newnode->next = NULL;
temp->next = newnode;
temp = temp->next; // newnode can also use instead of temp->next
}
void printList(struct node* node) {
while (node != NULL) {
printf(" %d ", node->data);
node = node->next;
}
}
}
int main()
{
struct node* head = NULL;
int n;
printf("Enter number of node to create");
scanf("%d",&n);
create(n);
printList(head);
return 0;
}
Change return type of the create function to return the address of the node like this: struct node * create(int n) and change return value to: return head;.
Finally, in main() save the returned address in head pointer: head = create(n);

Linked List C: add node to beginning, unexpected '0' value

I am trying to add a new node to the end of a linked list, I am able to add something, but when I print it out the node has a value of '0'. I thought this might be happening because I may have neglected to initialise a variable somewhere, or forgot to allocate memory said variable. but I can't get it to work.
Here is my source code:
my Linked List/struct:
#include<stdio.h>
typedef char DATA;
struct Node {
DATA d;
struct Node *next;
};
my printList function:
void printList(struct Node **head) {
struct Node *newNode = malloc(sizeof(struct Node));
struct Node *temp;
temp = *head;
printf("Linked list:");
while (temp->next != NULL) {
printf( " \n %d ", temp->d);
temp = temp->next;
}
printf("\n");
}
my insertNodeAtEnd to end function:
// inset data at end
void insertNodeAtEnd(struct Node *head) {
struct Node *newNode = malloc(sizeof(struct Node));
struct Node *currentNode, *temp;
temp = newNode;
currentNode = newNode;
printf("Enter a Node to insert at the end of the list \n");
scanf("%s", &newNode->d);
newNode->next = NULL;
if (head == NULL) {
head = newNode;
currentNode = newNode;
} else {
temp = head;
while (temp->next != NULL) {
temp = temp->next;
}
temp->next = newNode;
}
}
and my main():
int main() {
struct Node *newNode = (struct Node *)malloc(sizeof(struct Node));
struct Node *head = newNode;
struct Node *temp = newNode;
head->d = 1;
int i = 0;
printf("Enter 3 numbers");
for (i = 0; i < 3; i++) {
struct Node *newNode = (struct Node *)malloc(sizeof(struct Node));
scanf("%d", &temp->d);
temp->next = newNode;
temp = temp->next;
}
insertNodeAtEnd(head);
printList(&head);
return 0;
sorry for any messy code, I'm still reasonably new at this
Well, you have a couple of mistakes. Firstly, you need to add
temp->next = NULL;
before line insertNodeAtEnd(head);. The reason your code might work without this line is probably because your compiler initializes the pointer to NULL by default. For example in GCC you program is crashing without that line.Second problem is that you are defyning DATA type as a char, but reading it as int. It may cause crashing your application if processor working with big-engian addresses. You should change it to
typedef int DATA;
and also change
scanf("%s", &newNode->d);
to
scanf("%d", &newNode->d);
After that, change
while(temp->next!=NULL)
to
while(temp!=NULL)
because otherwise you are missing the last element. Then, you need to reorder a loop a little bit. This is the full working code with all fixes:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
typedef int DATA;
struct Node
{
DATA d;
struct Node *next;
};
void printList(struct Node **head)
{
struct Node *newNode;
struct Node *temp;
temp = *head;
printf("Linked list:");
while(temp!=NULL)
{
printf( " \n %d ", temp->d);
temp = temp->next;
}
printf("\n");
}
// inset data at end
void insertNodeAtEnd(struct Node **headPointer)
{
struct Node *head = *headPointer;
struct Node *newNode = malloc(sizeof(struct Node));
struct Node *currentNode, *temp;
temp = newNode;
currentNode = newNode;
printf("Enter a Node to insert at the end of the list \n");
scanf("%d", &newNode->d);
newNode->next = NULL;
if(head == NULL)
{
head = newNode;
currentNode = newNode;
}
else
{
temp = head;
while(temp->next!= NULL)
{
temp = temp->next;
}
temp->next = newNode;
}
*headPointer = head;
}
int main()
{
struct Node *newNode = (struct Node *)malloc(sizeof(struct Node));
struct Node *head = newNode;
struct Node *temp = newNode;
head->d = 1;
int i = 0;
printf("Enter 3 numbers: ");
for(i = 0; i < 3; i++)
{
if(i){
struct Node *newNode = (struct Node *)malloc(sizeof(struct Node));
temp->next = newNode;
temp = temp->next;
scanf("%d", &temp->d);
}else{
scanf("%d", &temp->d);
}
}
temp->next = NULL;
insertNodeAtEnd(&head);
printList(&head);
return 0;
}
UPDATE
I added a two more fixes. as #BLUEPIXY pointed out, there are a few more OP's mistakes. I've already spotted them, but I didn't fix it because they were not essential to what causes OP's problem. But, anyway, the mistakes are following:
Firstly, if the list is empty, function insertNodeAtEnd will not update pointer to the list because you are passing pointer to head of the list instead of pointer of a pointer to the head. It can be fixed by adding ** to the function argument type.
Secondly, you don't need to allocate memory while printing a list. You obviously just copied the code to each function, even to functions which doesn't require inserting nodes (like printList).
The above script is updated script including these two fixes.

why modifying the data field change the other field in link list

I want to insert node one by one in createDDCL() method and print all elements in printDDClinkList() method,but there is some strange error in createDDCL() method:
//BiDirection link list
typedef struct DDCL{
int data;
struct DDCL *priv;
struct DDCL *next;
}*BiDirectionLink;
BiDirectionLink createDDCL(){//带头结点的双向循环链表
int n = 0,i=0;
BiDirectionLink head = (BiDirectionLink)malloc(sizeof(BiDirectionLink));
BiDirectionLink newNode,lastNodw;
head->next = head;
head->priv = head;
lastNodw = head;
printf("how many node do you want?\n:");
scanf("%d",&n);
for (; i<n; i++) {//append new node to the last
newNode = (BiDirectionLink)malloc(sizeof(BiDirectionLink));
newNode->priv = lastNodw;
newNode->next = head;//new node's next always head
head->priv = newNode;//th privious one of the head always the last
lastNodw->next = newNode;
newNode->data = i;
lastNodw = newNode;
}
return head;
}
detail!!!!!!!!!!!
void printDDClinkList(BiDirectionLink head){
BiDirectionLink node = head->next;
while (node->next != head) {
printf("%d ",node->data);
node = node->next;
}
}
void testDDCLinkList(){
printDDClinkList(createDDCL());
}
int main(int argc, const char * argv[])
{
testDDCLinkList();
return 0;
}
This is the problem: You are allocating only enough memory for a pointer, not the whole struct.
This is what you did:
newNode = (BiDirectionLink)malloc(sizeof(BiDirectionLink));
Which is the same as this:
newNode = (struct DDCL *)malloc(sizeof(struct DDCL *));
But, that's what you wanted to do:
newNode = (struct DDCL *)malloc(sizeof(struct DDCL));
My recommendation? Never typedef to pointers.

Creating Linked List and printing the elements?

I want to create a linked list of numbers from 1 to 1000 and print the numbers.
Im using the function createList() to create the list and printList() to print the elements.
But the following code is crashing.
Can anybody please rectify. I'm new to linked list
#include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node* link;
};
struct node* head;
void deleteNode()
{
}
void createList()
{
int i;
struct node* temp = (struct node*)malloc(sizeof(struct node));
head = temp;
struct node* temp1 = (struct node*)malloc(sizeof(struct node));
for(i=0;i<10;i++)
{
temp->data = i+1;
temp->link = temp1;
temp1->link = temp++;
temp1++;
}
}
void printList()
{
struct node* temp = (struct node*)malloc(sizeof(struct node));
temp = head;
while(temp != NULL)
{
printf("%d ", temp->data);
temp = temp->link;
}
}
int main()
{
head = NULL;
createList();
printList();
return 0;
}
void createList(){
int i, size = 10;
struct node* temp = malloc(sizeof(struct node));
head = temp;
for(i=0;i<size;i++){
temp->data = i+1;
temp->link = i < size - 1 ? malloc(sizeof(struct node)) : NULL;
temp = temp->link;
}
}
void createList(){
int i, size = 10;
struct node* temp = malloc(size*sizeof(struct node));
head = temp;
if(temp){
for(i=0;i<size;i++){
temp->data = i+1;
temp->link = temp + 1;
++temp;
}
temp[-1].link = NULL;
}
}
void createList()
{
int i;
struct node *temp, *loc_head;
loc_head = head;
for(i=0;i<10;i++)
{
struct node* newnode = malloc(sizeof(struct node));
newnode->data = i+1;
newnode->link = NULL;
if(head == NULL) {
head=newnode;
loc_head = newnode;
}
else {
head->link = newnode;
head = newnode;
}
}
head = loc_head;
}
don't typecast the result of malloc
Given an array of elements, create a linked list from the array (one new node per
element, using the function that adds nodes to the end of a list).

Resources