#include <stdio.h>
#include <stdlib.h>
struct node{
int data;
struct node* next;
};
void append(struct node **head, int val){
struct node *new_node = (struct node*)malloc(sizeof(struct node));
new_node->data = val;
new_node->next = NULL;
if(*head==NULL){
*head=new_node;
return;
}
struct node *last = *head;
while(last->next!=NULL){
last = last->next;
}
last->next=new_node;//connect to starting od new node
}
void insertmid(struct node **head, int val, int index) {
struct node *new_node = (struct node*)malloc(sizeof(struct node));
new_node->data = val;
new_node->next = NULL;
// If index is 0, insert at the beginning
if (index == 0) {
new_node->next = *head;
*head = new_node;
return;
}
struct node *temp = *head;
// Traverse the list to find the insertion point
for (int i = 1; i < index-1; i++) {
if (temp != NULL) {
temp = temp->next;
}
}
// If temp is NULL, index is out of bounds, do nothing
if (temp == NULL) {
free(new_node);
return;
}
// ex [8,0x82] next one... tmp one is [7, empty]
new_node->next = temp->next;//new node connect the last node ending of temp//
//takes the address of the next member into it ex[7data, 0x82add] fromnext node
temp->next = new_node;//prev node..connect to starting of new node
}
int main() {
struct node *a;
append(&a,5);
append(&a,7);
insertmid(&a,6,2);
struct node *tmp = a;
while(tmp!=NULL){
printf("%d",tmp->data);
tmp = tmp->next;
}
}
To embed this program on your website, copy the following code and paste it into your website's HTML: