inserting in singly linked list in ascending order - c

Say I have a singly linked list of elements in ascending order that looks like:
A->B->D->E
I want to insert C in between B and D.
I know how to point C to D, but I don't know how to point B to C since the linked list does not keep track of the prev node.

While you are scanning down the list of nodes you have to keep two pointers: one points to the current node that you are interested in, and the other points to the previous node.

A possible implementation follows:
struct node {
int value;
struct node *next;
};
void sorted_insert(struct node **head, struct node *element) {
// Is the linked list empty?
if (*head == NULL) {
element->next = NULL;
*head = element;
return;
}
// Should we insert at the head of the linked list
if (element->value < (*head)->value) {
element->next = *head;
*head = element;
return;
}
// Otherwise, find the last element that is smaller than this node
struct node *needle = *head;
while (true) {
if (needle->next == NULL)
break;
if (element->value < needle->next->value)
break;
needle = needle->next;
}
// Insert the element
element->next = needle->next;
needle->next = element;
return;
}

You don't need to point B to C, or to maintain a pointer to the previous element. One method is:
Step to node D
malloc() a new node
Copy the data and next member from node D to your new node
Copy the data for node C into the existing node D (which now becomes node C)
Point the next member of the old node D to the new node.
For instance, excluding the possibility of inserting at the head of the list:
void insert(struct node * head, const int data, const size_t before)
{
assert(before > 0);
struct node * node = head;
while ( before-- && node ) {
node = node->next;
}
if ( !node ) {
fprintf(stderr, "index out of range\n");
exit(EXIT_FAILURE);
}
struct node * new_node = malloc(sizeof *new_node);
if ( !new_node ) {
perror("couldn't allocate memory for node");
exit(EXIT_FAILURE);
}
new_node->data = node->data;
new_node->next = node->next;
node->next = new_node;
node->data = data;
}

Why not keep track of the 'previous' node as you iterate through the list? Please forgive any syntactic shortcomings, as I haven't compiled this, but this should give you the idea.
struct node {
char name[ 10 ];
struct node *next;
};
struct list {
struct node *head;
};
void insert_C(struct list *list) {
struct node *new_node = malloc(sizeof(struct node));
if( new_node == NULL ) {
/* Error handling */
}
strcpy(new_node->name, "C");
struct node *pnode;
struct node *prev_node = NULL;
for( pnode = list->head; pnode->next != null; pnode = pnode->next ) {
if( !strcmp(pnode->name, "D") ) {
if( prev_node == NULL ) {
/* The 'C' node is going to be the new head. */
new_node->next = list->head;
list->head = new_node;
}
else {
prev_node->next = new_node;
new_node->next = pnode;
}
break;
}
/* Remember this node for the next loop iteration! */
prev_node = pnode;
}
}

Related

How can I insert a node in a singly linked list using recursion given: 1. a pointer to the head node 2. the index to insert the new node

The function below is the one I am trying to work on. The problem I am running into is that I do not know how to "keep" the pointer to the original head to the list as that is what I have to return after insertion.
There is no Driver code so everything must be done inside this function.
Because I must do this recursively I cannot just create a temporary node to point to the original head. I am just getting used to recursion and I cannot find a solution.
NOTE: There are some other problems with my function as I believe it wouldn't work well for inserting a new node into the beginning and end of the linked list but I am confident I could work out those edge cases.
The main thing I am trying to learn is how to "store" the original head of my list.
All help is appreciated.
Node* insert(Node* head, int index, int data)
{
if (head == NULL) return NULL; // if list is empty
if (index == 1) // if we have accessed node before insertion
{
struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));
new_node->next = head->next; // new_node->next now links to the node next in the list
head->next = new_node; // head->next links to new node
new_node->data = data; // assigns new node its data
return head; // not sure how to return original head
}
return insert(head->next, index - 1, data);
}
Node *insertRecursive(Node* head,int pos,int val)
{
if(pos==0 || head==NULL)
{
Node *newNode= new Node(val);
newNode->next=head;
head=newNode;
return head;
}
else
head->next = insertRecursive(head->next,pos-1,val);
}
For starters the parameter that specifies the position where a node has to be inserted should have an unsigned integer type, for example, size_t. Positions should start from 0.
The function can be defined the following way
struct Node * insert( struct Node *head, size_t pos, int data )
{
if (head == NULL || pos == 0 )
{
struct Node *new_node = malloc( sizeof( struct Node ) );
new_node->next = head;
new_node->data = data;
head = new_node;
}
else
{
head->next = insert( head->next, pos - 1, data );
}
return head;
}
Here is a demonstrative program
#include <stdio.h>
#include <stdlib.h>
struct Node
{
int data;
struct Node *next;
};
struct Node * insert( struct Node *head, size_t pos, int data )
{
if (head == NULL || pos == 0)
{
struct Node *new_node = malloc( sizeof( struct Node ) );
new_node->next = head;
new_node->data = data;
head = new_node;
}
else
{
head->next = insert( head->next, pos - 1, data );
}
return head;
}
void print( const struct Node *head )
{
for (; head != NULL; head = head->next)
{
printf( "%d -> ", head->data );
}
puts( "null" );
}
int main( void )
{
struct Node *head = NULL;
head = insert( head, 0, 3 );
print( head );
head = insert( head, 0, 0 );
print( head );
head = insert( head, 1, 1 );
print( head );
head = insert( head, 2, 2 );
print( head );
}
The program output is
3 -> null
0 -> 3 -> null
0 -> 1 -> 3 -> null
0 -> 1 -> 2 -> 3 -> null
Node* insert_Node_recursively(Node* head,int data,int position){
//Inserting on the first node.
if(position==0){
Node* newNode=new Node(data);
newNode->next=head;
head=newNode;
return head;
}
if((head->next==NULL && position==0) /*for adding on the end of the list */ || position==1 /*Inserting on node in between */){
Node* newNode=new Node(data);
newNode->next=head->next;
head->next=newNode;
return head;
}
//in case the position exceeds the total number of nodes
if(head->next==NULL && position>0){
return head;
}
else{
head->next=insert_Node_recursively(head->next,data,position-1);
}
return head;
}
this will work I think, covered all the aspects
//if you have created a node using class then here is the solution
//to insert a node at a position recurssively
Node * insertRecursive(Node * head, int data , int key)
{
if (head == NULL || key == 0)
{
Node * newNode = new Node(data);
newNode -> next = head;
head = newNode;
}
else
{
head -> next = insertRecursive(head -> next , data , key - 1);
}
return head;
}
//here is the full solution to add a node recursively at a position
#include<iostream>
using namespace std;
//the below code is for creation of class for node
class Node
{
public:
int data;
Node * next;
Node(int data) //constructor
{
this -> data = data;
next = NULL;
}
};
//the below code is for creation of linked list
//a terminator -1 is used to stop taking input
Node * takeInput()
{
int data;
cout<<"Enter the data of the node to be inserted ( use -1 to terminate
the insertion ) : ";
cin>>data;
Node * head = NULL;
Node * tail = NULL;
while(data != -1)
{
Node * newNode = new Node(data);
if(head == NULL)
{
head = newNode;
tail = newNode;
}
else
{
tail->next=newNode;
tail = tail -> next;
}
cout<<"Enter the data of the node to be inserted ( use -1 to
terminate the insertion ) : ";
cin>>data;
}
return head;
}
//the below code is to print the linked list
void print(Node * head)
{
if(head == NULL)
{
cout<<"The linked list id empty !"<<endl;
return;
}
Node * temp = head;
while(temp != NULL)
{
cout<<temp->data<<" ";
temp = temp -> next;
}
cout<<endl;
}
//the below part is the main solution to the problem
//insertion at a position using recursion
Node * insertRecursive(Node * head, int data , int key)
{
if (head == NULL || key == 0)
{
Node * newNode = new Node(data);
newNode -> next = head;
head = newNode;
}
else
{
head -> next = insertRecursive(head -> next , data , key - 1);
}
return head;
}
//this is the main from where all the function calls happen
int main()
{
int data, key;
Node * head = takeInput();
print(head);
cout<<"Enter the data of the node to be inserted : ";
cin>>data;
cout<<"Enter the position of insertion : ";
cin>>key;
head = insertRecursive(head,data,key);
print(head);
}

Insert a node into a doubly linked list in a sorted manner?

I am working on a problem in which I have a method that is supposed to insert a node into a doubly linked list in a sorted manner. Here is my node and list structure:
typedef struct NodeStruct Node;
//struct for each office item
struct NodeStruct {
int id;
struct NodeStruct *next;
struct NodeStruct *prev; //Create doubly linked list node
};
/** Structure for the whole list, including head and tail pointers. */
typedef struct {
/** Pointer to the first node on the list (or NULL ). */
Node *head;
Node *last;
} List;
When I attempt to print the list of items, the item what I am trying to insert does not appear. For instance, if I try to insert 15 into this list
1 -> 2 -> 3 -> 5 -> 7,
15 does not appear at the end. Here is my insert method:
void insert(int idInsert, List *list)
{
//Initialize data for node
int idInsert;
//Insert the record based on the ID if no duplicates exist
//Special case: insert at front if idInsert is less than the ID of the current head
if (idInsert < list->head->id) {
//Make the node with idInsert the first node
Node *new = (Node *)malloc(sizeof(Node)); //Allocate memory for the new node
//Add in data
new->id = idInsert;
new->next = list->head;
list->head = new;
} else { //Locate the node before the point of insertion
//Allocate memory for the node
Node *new = (Node *)malloc(sizeof(Node));
//Add in data
new->id = idInsert;
Node *current = list->head;
while (current->next != NULL && current->next->id < new->id) {
current = current->next;
}
new->next = current->next;
if (current->next != NULL) {
new->next->prev = new;
}
current->prev->next = new;
new->prev = current;
}
//Print this message if successful
printf("RECORD INSERTED: %d\n", idInsert);
}
I am also going to include some minimal reproducible code below:
#include <stdlib.h>
#include <stdio.h>
typedef struct NodeStruct Node;
//struct for each office item
struct NodeStruct {
int id;
struct NodeStruct *next;
struct NodeStruct *prev; //Create doubly linked list node
};
/** Structure for the whole list, including head and tail pointers. */
typedef struct {
/** Pointer to the first node on the list (or NULL ). */
Node *head;
Node *last;
} List;
List *list;
List *makeList();
void insert(int idInsert, List *list);
static void *addRecord(List *list, int newID);
static void printReverse(List *list);
int main(int argc, char **argv) {
//Create an empty list for you to start.
list = (List *)makeList();
addRecord(list, 1);
addRecord(list, 2);
addRecord(list, 3);
addRecord(list, 4);
addRecord(list, 7);
insert(15, list);
printReverse(list);
}
List *makeList()
{
List *list = (List *) malloc( sizeof( List ) );
list->head = NULL;
list->last = NULL;
return list;
}
void insert(int idInsert, List *list)
{
//Insert the record based on the ID if no duplicates exist
//Special case: insert at front if idInsert is less than the ID of the current head
if (idInsert < list->head->id) {
//Make the node with idInsert the first node
Node *new = (Node *)malloc(sizeof(Node)); //Allocate memory for the new node
//Add in data
new->id = idInsert;
new->next = list->head;
list->head = new;
} else { //Locate the node before the point of insertion
//Allocate memory for the node
Node *new = (Node *)malloc(sizeof(Node));
//Add in data
new->id = idInsert;
Node *current = list->head;
while (current->next != NULL && current->next->id < new->id) {
current = current->next;
}
new->next = current->next;
if (current->next != NULL) {
new->next->prev = new;
}
current->prev->next = new;
new->prev = current;
}
//Print this message if successful
printf("RECORD INSERTED: %d\n", idInsert);
}
static void *addRecord(List *list, int newID) {
//Allocate memory for the node
Node *new = (Node *)malloc(sizeof(Node));
//Add in data
new->id = newID;
new->prev = NULL;
//New node has no next, yet
new->next = NULL;
Node **next_p = &list->head;
while (*next_p) {
next_p = &(*next_p)->next;
}
*next_p = new;
list->last = new;
new->prev = *next_p;
return EXIT_SUCCESS;
}
static void printReverse(List *list) {
Node **tail = &list->last;
printf("LIST IN REVERSE ORDER:\n");
//Traversing until tail end of linked list
while (*tail) {
printf("Item ID: %d\n", (*tail)->id);
tail = &(*tail)->prev;
}
}
It seems like my addRecord method is working fine (this functions to add values to the end of the linked list), but my insert method is not working properly. When I execute the minimal reproducible code above, I am stuck in an infinite loop. My desired result after calling printReverse would be:
Item ID: 15
Item ID: 7
Item ID: 4
Item ID: 3
Item ID: 2
Item ID: 1
Could someone please point out what is going wrong in my insertion method?
Insert has three cases:
Insert at the start.
Insert at the middle.
Insert at the end.
Your weapon to sketch out your algorithm is a piece of a paper and a pencil, where you will draw what your code is doing.
Insert at the start
Your case for inserting at the start is not complete, since you need to set the new node's previous pointer to NULL, and the previous pointer of the node that was the old head should now be pointing to the newly created node.
That could be done like this:
Node *new = malloc(sizeof(Node)); //Allocate memory for the new node
list->head->prev = new;
new->prev = NULL;
// rest of your code
Insert at the end
Anyway, to answer your question, in your example, you could simply use the addRecord() method that appends a node in the list, when the node to be inserted goes to the end, like in your example, the node with id 15.
You can do it like this:
Node *current = list->head;
while (current->next != NULL && current->next->id < new->id) {
current = current->next;
}
// if the new node is the last one
if(current->next == NULL)
{
// append it to the list
addRecord(list, idInsert);
printf("RECORD INSERTED: %d\n", idInsert);
return;
}
assuming you are using the method addRecord() discussed in your previous question, and not the one you provide here.
But as #SomeProgrammerDude commented, you could simplify that by checking if the new node is greater than the last node, and if yes, you call the addRecord().
Insert at the middle
In the case of having only node with id 1 in the list, and you insert the node with id 15 at the end, this invokes Undefined Behavior:
current->prev->next = new;
since the current node (with id 1) has no previous node, thus it's set to NULL. So you are requesting for the next field in something not a structure or a union.. Same for having 1 and 15 already in the list, and trying to insert 5.
Try changing that to:
current->next = new;
However, with your code, you will request the id of list->head, even if the list is empty, meaning that head (and last) pointer is NULL. That will invoke Undefined Behavior (UB), which is likely to result in a segmentation fault.
For that reason, in the following code I will first check if the list is empty or if the new node shall be inserted at the end, since in both cases it is enough to just call the addRecord() method (which appends a node to the list).
The condition of the if statement is going to be this:
if (list->last == NULL || idInsert > list->last->id)
which, due to short circuiting is going to be evaluated in the following order:
If the last pointer is NULL, then for sure the condition will be evaluated to true since the operator is the logical OR, so a single true operand will suffice to determine what the overall outcome of the condition is going to be. That means, that it won't evaluate the second operand, so the last pointer will not be dereferenced (which would invoke UB, since we would be requesting the id of NULL).
Putting everything together:
#include <stdlib.h>
#include <stdio.h>
typedef struct NodeStruct Node;
//struct for each office item
struct NodeStruct {
int id;
struct NodeStruct *next;
struct NodeStruct *prev; //Create doubly linked list node
};
/** Structure for the whole list, including head and tail pointers. */
typedef struct {
/** Pointer to the first node on the list (or NULL ). */
Node *head;
Node *last;
} List;
List *list;
List *makeList();
void insert(int idInsert, List *list);
static void *addRecord(List *list, int newID);
static void printReverse(List *list);
int main(void) {
//Create an empty list for you to start.
list = (List *)makeList();
addRecord(list, 1);
addRecord(list, 2);
addRecord(list, 3);
addRecord(list, 4);
addRecord(list, 7);
insert(6, list);
insert(0, list);
insert(15, list);
printReverse(list);
}
List *makeList()
{
List *list = (List *) malloc( sizeof( List ) );
list->head = NULL;
list->last = NULL;
return list;
}
//Insert the record based on the ID if no duplicates exist
void insert(int idInsert, List *list)
{
// Insert at end, if list is empty or if id is greater than all existing ids
// Short circuting protects from derefercing a NULL pointer
if (list->last == NULL || idInsert > list->last->id) {
addRecord(list, idInsert);
} else if (idInsert < list->head->id) { // Insert at start
//Make the node with idInsert the first node
Node *new = malloc(sizeof(Node)); //Allocate memory for the new node
list->head->prev = new;
new->prev = NULL;
//Add in data
new->id = idInsert;
new->next = list->head;
list->head = new;
} else { // Insert in the middle
//Locate the node before the point of insertion
//Allocate memory for the node
Node *new = malloc(sizeof(Node));
//Add in data
new->id = idInsert;
Node *current = list->head;
while (current->next != NULL && current->next->id < new->id) {
current = current->next;
}
new->next = current->next;
if (current->next != NULL) {
new->next->prev = new;
}
current->next = new;
new->prev = current;
}
//Print this message if successful
printf("RECORD INSERTED: %d\n", idInsert);
}
static void *addRecord(List *list, int newID)
{
//Allocate memory for the node
Node *new = malloc(sizeof(Node));
//Add in data
new->id = newID;
new->prev = list->last;
new->next = NULL;
list->last = new;
// if list is empty
if(!list->head)
{
list->head = new;
return EXIT_SUCCESS;
}
Node **next_p = &list->head;
while (*next_p) {
next_p = &(*next_p)->next;
}
*next_p = new;
return EXIT_SUCCESS;
}
static void printReverse(List *list) {
Node **tail = &list->last;
printf("LIST IN REVERSE ORDER:\n");
//Traversing until tail end of linked list
while (*tail) {
printf("Item ID: %d\n", (*tail)->id);
tail = &(*tail)->prev;
}
}
Output:
RECORD INSERTED: 6
RECORD INSERTED: 0
RECORD INSERTED: 15
LIST IN REVERSE ORDER:
Item ID: 15
Item ID: 7
Item ID: 6
Item ID: 4
Item ID: 3
Item ID: 2
Item ID: 1
Item ID: 0
Appendix
Notice how I approach the special cases of insert at the start and end before tackling the middle case. That is because your list has head and last pointers, these special insertions can get done in constant time, O(1), since you don't have to scan (iterate over) the list.
However, in the middle insertion, you have to scan the list, in order to locate the appropriate index, and then insert the node at that index.
Remember: the operation of traversing a list can take linear time (traversing the whole list), which in asymptotic notation is O(n), where n is the size of the list.
PS: I also checked the next pointer, by using the print (in normal order) method discussed in the linked question.
PPS: When you are done, do not forget to free the list. I have a method for this in List (C), which is the same for a double linked list, except, that you also have to set the head and last pointers to NULL too.

Adding a node to the head of the linked list

I would like to add a node in a sorted linked list based on the number. This is the struct:
struct node {
int number;
struct node *next;
}
I am able to add to the sorted linked list correctly but can't get it to change head.
Unfortunately I can't change the format of the function declaration so this is my function:
int create(struct node *head, int number) {
struct node *newNode = malloc(sizeof(struct node));
newNode->number = number;
struct node *current = head;
if (current->number == -1) {
newNode->next = NULL;
*head= *newNode;
return 1;
}
//Checking if head's number is bigger than init
if (current->number > number) {
newNode->next = current;
*head = *newNode;
} else {
while(current->next != NULL && (current->number <= number)) {
current = current->next;
}
newNode->next = current->next;
current->next = newNode;
}
return 1;
}
the call to the function is (Note I also can't change this):
struct node *list;
list = initializeList();
int num;
num = create(list, 5);
num = create(list, 1);
After the second call, the list should be 1->5. But it becomes 1->1->1->1->.....
Edit: Code to Initialize list:
struct node * initializeList() {
struct node *head;
head = malloc(sizeof(struct node));
head->next = NULL;
head->number = -1;
return head;
}
I made a few edits to the create function to fix the problem.
First, if the head of the list has number == -1 then no new node should be allocated, since you are just replacing the number.
Second, if you need to insert a node, the previous node needs to know where to the next node goes, so you can't just replace the previous node with the new node. You need to either point the previous node to the new node and point the new node to the displaced node; or you can copy the current node into the new node, and put the number for the new node into the current, and point it to the new node. The second works better here, since it does not require changing the head (which we can't do if it needs to go at the front).
int create(struct node *head, int number) {
struct node *current = head;
if (current->number == -1) {
current->number = number;//just replace the number, no need for anything else
return 1;
}
//allocate only if we must insert
struct node *newNode = malloc(sizeof(struct node));
//no longer need to check if head
while(current->next != NULL && (current->number <= number)) {
current = current->next;
}
if(current->next == NULL && current->number < number) {//check if number needs to go at the end
current->next = newNode;
newNode->next = NULL;
newNode->number = number;
} else {
*newNode = *current;//newNode will go after current, but with current's values
current->number = number;//replace current with the number to "insert" it
current->next = newNode;//point to the next node
}
return 1;
}
assign an index value to the node and shift the other elements by one. I mean you can add one to the each value of the other element and make in iterate in a loop.

Inserting a new node into a doubly linked list after a given node

This function inserts a new node after a given node in a doubly linked list.
It works well unless the list is empty or when given node is NULL.
I have tried to solve this problem by inserting the new node as head, but it doesn't add the new node or does problems when adding a second node.
void insert(Polynomial** node, int new_data, int pow) {
Polynomial* new_node = ( Polynomial*)malloc(sizeof( Polynomial));
new_node->num = new_data;
new_node->pow = pow;
if ((*node) == NULL) {
new_node->prev = NULL;
(*node) = new_node;
return;
}
new_node->next = (*node)->next;
(*node)->next = new_node;
new_node->prev = (*node);
if (new_node->next != NULL)
new_node->next->prev = new_node;
}
Struct:
typedef struct Polynomial {
int num;
int pow;
struct Polynomial* next;
struct Polynomial* prev;
}Polynomial;
When you create a new list, the first node's next pointer is unspecified. This could lead to undefined behaviour when inserting the second node, e.g. the 0xcdcdcdcd value you saw. Set it to null before returning:
if ((*node) == NULL) {
new_node->prev = new_node->next = NULL;
(*node) = new_node;
return;
}

Linked list in C – methods

Suppose we have doubly linked list of nodes
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int value;
struct Node* next;
struct Node* prev;
} Node;
typedef struct LinkedList {
Node *first;
Node *last;
} LinkedList;
void initList(LinkedList* l) {
l->first = NULL;
l->last = NULL;
}
and I have to code method, which inserts a new node with given value to the end of the list and returns a pointer to the new node. My attempt follows:
Node *insert(LinkedList *list, int value) {
Node node;
node.value = value;
node.prev = list->last;
node.next = NULL;
if (list->last != NULL){
(list->last)->next = &node;
}else{
list->first = &node;
list->last = &node;
}
return &node;
}
It seems, that insertion in the empty list works, but it doesn't for a non-empty one.
(There are implementation tests, which tell me if an insertion was successful or not. I can post the codes of them, but don't think it's important).
So please, where are the mistakes?
There is a warning in the log (the 51st line is that with 'return &node')
C:\...\main.c|51|warning: function returns address of local variable [-Wreturn-local-addr]|
Is that serious problem? And how to remove it?
Thank you for the answers, but I think there is still a problem with non-empty lists, because according to the test, this fails:
void test_insert_nonempty(){
printf("Test 2: ");
LinkedList l;
initList(&l);
Node n;
n.value = 1;
n.next = NULL;
l.first = &n;
l.last = &n;
insert(&l, 2);
if (l.last == NULL) {
printf("FAIL\n");
return;
}
if ((l.last->value == 2) && (l.last->prev != NULL)) {
printf("OK\n");
free(l.last);
}else{
printf("FAIL\n");
}
}
Node node; is a local variable in your function insert. It is "destroyed" as soon as your function terminates and is not longer defined. Returning a pointer to local variable of a function is undefined behavior. You have to allocate dynamic memory. Dynamically allocate memory is reserved until you free it:
Node *insert(LinkedList *list, int value) {
Node *node = malloc( sizeof( Node ) ); // allocate dynamic memory for one node
if ( node == NULL )
return NULL; // faild to allocate dynamic memory
node->value = value;
node->prev = list->last;
node->next = NULL;
if ( list->first == NULL )
list->first = node; // new node is haed of list if list is empty
else // if ( list->last != NULL ) // if list->first != NULL then list->last != NULL
list->last->next = node; // successor of last node is new node
list->last = node; // tail of list is new node
return node;
}
Note to avoid memory leaks you have to free each node of the list, when you destroy the list.
You are returning address of non-static local variable which will vanish on returning from function, and dereferencing the address after returning from the function invokes undefined behavior.
You have to allocate some buffer and return its address.
Node *insert(LinkedList *list, int value) {
Node *node = malloc(sizeof(Node));
if (node == NULL) return NULL;
node->value = value;
node->prev = list->last;
node->next = NULL;
if (list->last != NULL){
(list->last)->next = node;
}else{
list->first = node;
list->last = node;
}
return node;
}
You have to allocate the new node dynamically.
Otherwise variable node in your function
Node *insert(LinkedList *list, int value) {
Node node;
//...
is a local variable of the function that will not be alive after exiting the function. As result any pointer to the variable used to access it will be invalid.
The function can look like
Node * insert( LinkedList *list, int value )
{
Node *node = malloc( sizeof( Node ) );
if ( node != NULL )
{
node->value = value;
node->prev = list->last;
node->next = NULL;
if ( list->last != NULL )
{
list->last->next = node;
}
else
{
list->first = node;
}
list->last = node;
}
return node;
}

Resources