Browse Source

Linked List in C v1.0

master
Jessy K. Martz 2 years ago
parent
commit
b88d7c978e
1 changed files with 150 additions and 0 deletions
  1. 150
    0
      main.c

+ 150
- 0
main.c View File

@@ -0,0 +1,150 @@
#include <stdio.h>
#include <stdlib.h>

typedef struct node {
int data;
struct node *next;
} node_t;

void print_list(node_t *);
void add_at_beginning(node_t **, int);
void add_at_end(node_t *, int);
void add_node_at_index(node_t **, int, int);
int remove_last_node(node_t *);
int remove_first_node(node_t **);
int remove_node_by_index(node_t **, int);

int main(void)
{
int data;
node_t *head = NULL;
head = (node_t *)malloc(sizeof(node_t));

printf("Linked List with C.\n");

head->data = 1;
head->next = NULL;
print_list(head);


printf("\n-Made by CodeNoSchool ! Check it on YouTube, Twitter, GitHub!\n");

return 0;
}

void print_list(node_t *head)
{
node_t *current = head;

while (current != NULL)
{
printf("%d\n", current->data);
current = current->next;
}
}

void add_at_beginning(node_t **head, int data)
{
node_t *new_node = NULL;
new_node = (node_t *)malloc(sizeof(node_t));

new_node->data = data;
new_node->next = *head;
*head = new_node;
}

void add_at_end(node_t *head, int data)
{
node_t *current = head;
node_t *new_node = NULL;
new_node = (node_t *)malloc(sizeof(node_t));

new_node->data = data;
new_node->next = NULL;

while (current->next != NULL)
{
current = current->next;
}

current->next = new_node;
}

int remove_last_node(node_t *head)
{
node_t *current = head;
int data;

while (current->next->next != NULL)
{
current = current->next;
}

data = current->next->data;
free(current->next);
current->next = NULL;

return data;
}

int remove_first_node(node_t **head)
{
int data;
data = (*head)->data;
*head = (*head)->next;
free(*head);

return data;
}

int remove_node_by_index(node_t **head, int p)
{
if (p == 0)
return remove_first_node(head);

int data;
int i;
node_t *current = *head;

for(i = 0; i < p - 1; i++)
{
current = current->next;
}

data = current->next->data;
free(current->next);
current->next = NULL;

return data;
}

void add_node_at_index(node_t **head, int p, int data)
{
if (p == 0)
{
add_at_beginning(head, data);
} else
{
node_t *current = *head;

if (current->next == NULL)
{
add_at_end(*head, data);
} else
{
int i;

for(i = 0; i < p - 1; i++)
{
current = current->next;
}

node_t *new_node = NULL;
new_node = (node_t *)malloc(sizeof(node_t));
new_node->data = data;
new_node->next = current->next;
current->next = new_node;
}
}
}

Loading…
Cancel
Save