0% found this document useful (0 votes)
7 views

Creation and Insertion at Specified Index Single Linked List

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

Creation and Insertion at Specified Index Single Linked List

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 4

Creation and insertion at specified index

// Online C compiler to run C program online

#include <stdio.h>

#include <stdlib.h>

struct Node {

int data;

struct Node *nextAddr;

};

void create (struct Node **headPointer , int data)

struct Node *node;

node = (struct Node *)malloc(sizeof(struct Node));

node -> data = data;

node -> nextAddr = NULL;

//nothing in linked list

if (*headPointer == NULL)

*headPointer = node;

return;

//if list is not empty

struct Node *tempNode;

tempNode = *headPointer;

while (tempNode -> nextAddr != NULL)


{

tempNode = tempNode -> nextAddr;

tempNode -> nextAddr = node;

void insertPosition(struct Node **p, int data, int pos)

struct Node* newNode = (struct Node*) malloc(sizeof(struct Node));

newNode->data = data;

newNode->nextAddr = NULL;

if (pos == 0)

newNode->nextAddr = *p;

*p = newNode;

return;

struct Node* current = *p;

for (int i = 0; current != NULL && i < pos - 1; i++) {

current = current->nextAddr;

if (current == NULL) {

printf("Position is out of bounds\n");

free(newNode);
return;

newNode->nextAddr = current->nextAddr;

current->nextAddr = newNode;

void printLinkList(struct Node **headPointer)

struct Node *tempNode;

tempNode = *headPointer;

while (tempNode -> nextAddr != NULL)

printf("%d\n" , tempNode -> data);

tempNode = tempNode -> nextAddr;

printf("%d\n" , tempNode -> data);

int main() {

struct Node *head;

create(&head , 10);

create(&head , 20);

create(&head , 30);

create(&head , 40);

insertPosition(&head , 50 , 2);
printLinkList(&head);

return 0;

You might also like