I am trying to create a linked list of strings in C and have had problems adding the first Node into the list. For whatever reason my program prints NULL even though I reference the head variable to newNode but it does not copy the string from struct pointer to struct pointer. Any help is appreciated. Thanks!
#include "stdafx.h"
#include <stdlib.h>
#include <string.h>
typedef struct stringData {
char *s;
struct stringData *next;
} Node;
Node *createNode(char *s) {
Node *newNode = (Node *)malloc(sizeof(Node));
newNode->s = s;
newNode->next = NULL;
return newNode;
}
void insert(Node *head, Node *newNode) {
if (head == NULL) {
head->s = newNode->s;
head = newNode;
}
}
void printList(Node *head) {
while (head != NULL) {
printf("%s\n", head->s);
head = head->next;
}
}
int main()
{
Node *head = createNode(NULL);
Node *a = createNode("A");
insert(head, a);
printList(head);
return 0;
}
Following code snippet is wrong:
void insert(Node *head, Node *newNode) {...}
...
insert(head, a);
You need to pass the pointer by reference. Currently you are changing local copy (argument).
Fix
Change your insert as:
void insert(Node **head, Node *newNode) {...}
And call as:
insert(&head, a);
What elseAtleast insert (and possibly) more functions are not fool-proof (guaranteed null pointer dereference, else case not handled etc). You need to debug and fix many such cases. Working your approach properly on paper before coding may help.
Here is a modified version of the code that gives an example of inserting new nodes at both the start of a list and the end of a list. In fact, the insert function could be used to insert a new node at any position in the list, since all it needs is a pointer to a link and a pointer to the node to be inserted.
#include <stdlib.h>
#include <stdio.h>
typedef struct stringData {
char *s;
struct stringData *next;
} Node;
Node *createNode(char *s) {
Node *newNode = (Node *)malloc(sizeof(Node));
newNode->s = s;
newNode->next = NULL;
return newNode;
}
void insert(Node **link, Node *newNode) {
newNode->next = *link;
*link = newNode;
}
void printList(Node *head) {
while (head != NULL) {
printf("%s\n", head->s);
head = head->next;
}
}
int main(void)
{
Node *head = NULL;
Node *tail = NULL;
Node *n;
n = createNode("B");
// First node at start of list - head is updated.
insert(&head, n);
// First node is also the tail.
tail = n;
n = createNode("A");
// Insert node at start of list - head is updated.
insert(&head, n);
n = createNode("C");
// Insert node at end of list.
insert(&tail->next, n);
// Update tail.
tail = n;
printList(head);
return 0;
}
Related
This question already has answers here:
Linked lists - single or double pointer to the head
(3 answers)
What is the reason for using a double pointer when adding a node in a linked list?
(15 answers)
Closed 10 months ago.
#include<stdio.h>
#include<stdlib.h>
void insert_front(struct node* head, int block_number);
void insert_rear(struct node* head, int block_number);
void print_list(struct node* head);
struct node {
int block_number;
struct node* next;
};
int main(void)
{
struct node* list = NULL;
insert_front(list, 10);
insert_rear(list, 20);
insert_front(list, 30);
insert_rear(list, 40);
print_list(list);
return 0;
}
void insert_front(struct node* head, int block_number)
{
struct node* p = malloc(sizeof(struct node));
p->block_number = block_number;
p->next = head;
head = p;
return head;
}
void insert_rear(struct node* head, int block_number)
{
struct node* p = malloc(sizeof(struct node));
p->block_number = block_number;
p->next = NULL;
if (head == NULL) {
head = p;
}
else {
struct node* q = head;
while (q->next != NULL) {
q = q->next;
}
q->next = p;
}
}
void print_list(struct node* head)
{
struct node* p = head;
while (p != NULL) {
printf("--> %d ", p->block_number);
p = p->next;
}
printf("\n");
}
When I ran it, there was no result at all.
Now, in the insert_front function p->block_number = block_number, a message appears saying that the NULL pointer 'p' is being dereferenced... (The same thing appears in the insert_rear function.)
Could it be that I am declaring the pointer wrong?
Both insert_front and insert_rear need to convey possibly head modification back to the caller, and the caller needs to reap that information. Both should be declared to return struct node *, do so, and the code in main react accordingly. E.g.:
#define _POSIX_C_SOURCE 200809L
#include <stdio.h>
#include <stdlib.h>
struct node * insert_front(struct node *head, int block_number);
struct node * insert_rear(struct node *head, int block_number);
void print_list(struct node *head);
struct node
{
int block_number;
struct node *next;
};
int main(void)
{
struct node *list = NULL;
list = insert_front(list, 10);
list = insert_rear(list, 20);
list = insert_front(list, 30);
list = insert_rear(list, 40);
print_list(list);
return 0;
}
struct node *insert_front(struct node *head, int block_number)
{
struct node *p = malloc(sizeof(struct node));
p->block_number = block_number;
p->next = head;
head = p;
return head;
}
struct node *insert_rear(struct node *head, int block_number)
{
struct node *p = malloc(sizeof(struct node));
p->block_number = block_number;
p->next = NULL;
if (head == NULL)
{
head = p;
}
else
{
struct node *q = head;
while (q->next != NULL)
{
q = q->next;
}
q->next = p;
}
return head;
}
void print_list(struct node *head)
{
struct node *p = head;
while (p != NULL)
{
printf("--> %d ", p->block_number);
p = p->next;
}
printf("\n");
}
Output
--> 30 --> 10 --> 20 --> 40
I leave the memory leaks for you to resolve.
In C all variables are passed by value – if you pass a pointer, then it is copied, too (not the pointed to object, of course...), and function parameters, apart from being initialised from outside, are nothing more than local variables. Thus via head = p; you just assign the local copy of the outside pointer, not the latter itself!
To fix that you have two options:
Return the new head and make the user responsible for re-assigning the returned value to his own head pointer.
Accept the head as pointer to pointer.
With second approach a user cannot forget to re-assign the (potentially) new head, so that's what I'd go with:
void insert_whichEver(node** head, int block_number)
{
// use `*head` where you had `head` before...
}
void demo()
{
node* head = NULL;
insert_front(&head, 1012);
}
And in insert_front drop return head;, a function with void cannot return anything concrete and does not require a return at all (but bare return; can be used to exit a function prematurely).
#include <stdlib.h>
#include <stdio.h>
struct node {
int data;
struct node *next;
};
void addLast(struct node **head, int value);
void printAll(struct node *head);
struct node *head1 = NULL;
int main() {
addLast(&head1, 10);
addLast(&head1, 20);
addLast(&head1, 30);
addLast(&head1, 40);
printAll(head1);
return 0;
}
void addLast(struct node **head, int value) {
struct node *newNode = (struct node*)malloc(sizeof(struct node));
newNode->data = value;
if (*head == NULL) {
*head = newNode;
(*head)->next = NULL;
} else {
struct node **temp = head;
while ((*temp)->next != NULL) {
*temp = (*temp)->next;
}
(*temp)->next = newNode;
newNode->next = NULL;
}
}
void printAll(struct node *head) {
struct node *temp = head;
while (temp != NULL) {
printf("%d->", temp->data);
temp = temp->next;
}
printf("\n");
}
addLast() will append the new node at the end of the list, with printAll(), I am printing entire list.
Every time when I am printing the list, I can only see the last two nodes.
Can anyone please help, why loop is not iterating over entire list ?
The function addLast is too complicated and as result is wrong due to this statement
*temp = (*temp)->next;
in the while loop. It always changes the head node.
Define the function the following way
int addLast( struct node **head, int value )
{
struct node *newNode = malloc( sizeof( struct node ) );
int success = newNode != NULL;
if ( success )
{
newNode->data = value;
newNode->next = NULL:
while( *head ) head = &( *head )->next;
*head = newNode;
}
return success;
}
Take into account that there is no need to declare the variable head1 as global. It is better to declare it inside the function main.
Also all the allocated memory should be freed before exiting the program.
I got a linked list, which should save the Outcome (W or L) and the gained/lost points for each match. All good so far, but I'm getting trouble when the head does not exist/is empty. I also realized I have a pretty bad overview of how to implement linked lists, anyone got good and understandable resources? Anyway this is my code:
#include <stdio.h>
#include <stdlib.h>
struct node {
int point;
char outcome;
struct node *next;
};
void add(struct node *data){
if(data == NULL){
data = malloc(sizeof(struct node));
printf("Outcome and points?\n");
int point;
char outcome;
scanf("%c %d",&outcome,&point);
fgetc(stdin);
data->point=point;
data->outcome=outcome;
data->next=NULL;
}else{
struct node *current= data;
while(current->next != NULL){
current = current->next;
}
current->next = malloc(sizeof(struct node));
current=current->next;
printf("Outcome and points?\n");
int point;
char outcome;
scanf("%c %d",&outcome,&point);
fgetc(stdin);
current->point=point;
current->outcome=outcome;
current->next=NULL;
}
}
void print(struct node *data){
struct node *current = data;
while(current != NULL){
printf("%c with %3d\n",current->outcome,current->point);
current = current->next;
}
}
int main()
{
struct node *head=NULL;
add(head);
add(head);
add(head);
print(head);
}
Any help would be appreciated :)
When you execute:
void add(struct node *data){
if(data == NULL){
data = malloc(sizeof(struct node));
the value of head does not change in the calling function.
Suggest a change of strategy.
struct node* add(struct node *head)
{
if(head == NULL){
head = malloc(sizeof(struct node));
printf("Outcome and points?\n");
int point;
char outcome;
scanf("%c %d",&outcome,&point);
fgetc(stdin);
head->point=point;
head->outcome=outcome;
head->next=NULL;
}else{
struct node *current= head;
while(current->next != NULL){
current = current->next;
}
current->next = malloc(sizeof(struct node));
current=current->next;
printf("Outcome and points?\n");
int point;
char outcome;
scanf("%c %d",&outcome,&point);
fgetc(stdin);
current->point=point;
current->outcome=outcome;
current->next=NULL;
}
return head;
}
And, then change the usage:
int main()
{
struct node *head = add(NULL);
add(head);
add(head);
print(head);
}
You can simplify the code by starting the list with an anchor node. An anchor node is a node that is only used for its next pointer. In the code below, the call to calloc creates the anchor node, and sets all of the fields in the anchor to 0. In other words, a node is created with next == NULL.
Note that when printing the list, the for loop starts by skipping the anchor node with for (list = list->next;...)
#include <stdio.h>
#include <stdlib.h>
struct node
{
int point;
char outcome;
struct node *next;
};
void add( struct node *list )
{
struct node *data;
data = malloc(sizeof(struct node));
data->next = NULL;
printf("Outcome and points?\n");
scanf("%c %d",&data->outcome,&data->point);
fgetc(stdin);
while (list->next != NULL)
list = list->next;
list->next = data;
}
void print( struct node *list )
{
for (list = list->next; list != NULL; list = list->next)
printf("%c with %3d\n", list->outcome, list->point);
}
int main()
{
struct node *head = calloc( 1, sizeof(struct node) );
add(head);
add(head);
add(head);
print(head);
}
Side note: I've omitted some error checking to keep things simple, you should really be checking the return values from calloc, malloc, and scanf and handle any errors. And, of course, you should free all of the nodes at the end.
I want to make a double linked list and I have a problem with accessing fields in the struct. This is my code:
#include <stdio.h>
#include <stdlib.h>
typedef struct node{
int val;
struct node * next;
struct node * prev;
}node;
void insert(int val, node **head)
{
node * temp= *head;
node * temp2=(node *)malloc(sizeof(node));
node * temp3=(node *)malloc(sizeof(node));
temp2->val=val;
temp2->prev=NULL;
temp2->next=*head;
*head=temp2;
temp2->next->prev=temp2;
}
void print(node* head)
{
node* temp=head;
while(temp!=NULL)
{
printf("%d ", temp->val);
temp=temp->next;
}
}
int main()
{ node * head=NULL;
insert(1, &head);
insert(2, &head);
print(head);
return 0;
}
I get a crash at temp2->next->prev, and I don't understand why. Am I not allowed to access the prev field of the temp2->next node? I tried writing (temp2->next)->prev but also doesn't work. Is there any way that I cant make that work?
When you insert the first node, *head, and therefore temp->next, is NULL. Check that case:
void insert(int val, node **head)
{
node *temp= malloc(sizeof(*temp));
temp->val = val;
temp->prev = NULL;
temp->next = *head;
*head = temp;
if (temp->next) temp->next->prev = temp;
}
(I've removed the unused variables and lost the cast on malloc.)
A doubly linked list should probably have a tail, too. In that case, update the tail when you append an item at the head of an empty list.
try this:
void insert(int val, node **head)
{
if(*head == NULL){
node * temp2=(node *)malloc(sizeof(node));
temp2->val=val;
*head = temp2;
}
else{
node * temp= *head;
node * temp2=(node *)malloc(sizeof(node));
temp2->val=val;
temp2->prev=NULL;
temp2->next=temp;
temp->prev = temp2;
}
}
Most likely head was not initialized
As I have understood you always insert a new node before the head though in double linked list you have to add new nodes usually at the tail of the list. As a double linked list usually have two sides then there is a sense to define two functions: push_front and push_back. Your function insert corresponds to function push_front.
Nevertheless function insert could look the following way
void insert( int val, node **head )
{
node *temp = ( node * )malloc( sizeof( node ) );
temp->val = val;
temp->prev = NULL;
temp->next = *head;
if ( *head ) ( *head )->prev = temp;
*head = temp;
}
It would be better if you would define one more structure named as for example List (or whatever) and that could be defined as
struct List
{
node *head;
node *tail;
};
Also you could add one more data member - a count of the nodes in the list, For example
struct List
{
node *head;
node *tail;
size_t count;
};
Also do not forget to write a function that would delete all nodes of the list when it is not needed any more.
I have the following single linked list,I always get the length as 1,even if i push 3 elements,and always only one node is created.Please help.Thanks.
#include <stdio.h>
struct node
{
int data;
struct node *next;
};
void push(struct node **head,int data)
{
struct node *temp = (struct node*)malloc(sizeof(struct node));
temp->data=data;
if(*head == NULL)
{
*head=temp;
}
else
{
temp->next=*head;
*head=temp;
}
}
int length(struct node *head)
{
struct node *temp = head;
int count=0;
if(temp !=NULL)
{
count++;
printf("%d",temp->data);
temp=temp->next;
}
return count;
}
int main()
{
int a;
struct node *head=NULL;
push(&head,1);
push(&head,2);
push(&head,3);
a=length(head);
printf("%d",a);
return 0;
}
Replace if by while in the length function
In your length function, change this line:
if(temp !=NULL)
to this:
while(temp != NULL)
Have you noticed the structure of your length method? You are using an if statement where a loop would be appropriate. You are getting the answer of 1 because you are only executing the count ++ statement once.
Hope this helps.
The error comes from push() function. If head is not null you need to iterate through the list to the last node. And as said before while instead if
# include <stdlib.h>
void push(struct node **head,int data)
{
struct node *temp;
temp = malloc (sizeof *temp);
temp->data = data;
temp->next = *head;
*head = temp;
}