Adding items to the beginning of a linked list
void push(node_t ** head, int val) {
node_t * new_node;
new_node = (node_t *) malloc(sizeof(node_t));
new_node->val = val;
new_node->next = *head;
*head = new_node;
}
Adding items to the beginning of a linked list
void push(node_t ** head, int val) {
node_t * new_node;
new_node = (node_t *) malloc(sizeof(node_t));
new_node->val = val;
new_node->next = *head;
*head = new_node;
}
adding a node at the beginning of a linked list in c
/*
* STEPS TO INSERT A NODE AT THE BEGINNING OF A LINKED LIST
* 1. Create a new node
* 2. Make the new node point to the head
* 3. Asign the new node to the head
*/
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
/**
* USED THIS STRUCT IN THIS PROGRAM
* struct list_s - singly linked list
* @str: string - (malloc'ed string)
* @len: length of the string
* @next: points to the next node
*/
typedef struct list_s
{
char *str;
unsigned int len;
struct list_s *next;
} list_t;
/**
* add_node - adds a new node at the beginning
* of a list_t list.
* @head: A pointer to the head of the list_t list.
* @str: The string to be added to the list_t list.
*
* Return: If the function fails - NULL.
* Otherwise - the address of the new element.
*/
list_t *add_node(list_t **head, const char *str)
{
char *dup;
int len;
list_t *new;
new = malloc(sizeof(list_t));
if (new == NULL)
return (NULL);
dup = strdup(str);
if (dup == NULL)
{
free(new);
return (NULL);
}
for (len = 0; str[len];)
len++;
new->str = dup;
new->len = len;
new->next = *head;
*head = new;
return (new);
}
Copyright © 2021 Codeinu
Forgot your account's password or having trouble logging into your Account? Don't worry, we'll help you to get back your account. Enter your email address and we'll send you a recovery link to reset your password. If you are experiencing problems resetting your password contact us