Untitled
unknown
plain_text
2 years ago
1.9 kB
7
Indexable
#include<stdio.h>
#include<stdlib.h>
struct node{
int data;
struct node* next;
};
struct node* insertatfirst(int data,struct node* head){
struct node* ptr= (struct node*)malloc(sizeof(struct node));
ptr->next=head;
ptr->data=data;
}
struct node* insertafternode(int data,struct node* prevnode,struct node* head){
struct node* ptr= (struct node*)malloc(sizeof(struct node));
ptr->data=data;
ptr->next=prevnode->next;
prevnode->next=ptr;
}
struct node* insertatindex(int data,struct node* head,int index){
struct node* ptr= (struct node*)malloc(sizeof(struct node));
struct node* p=head;
int i=0;
while(i!= index-1){
p=p->next;
i++;
}
ptr->data=data;
ptr->next=p->next;
p->next=ptr;
}
struct node* insertatend(int data,struct node* head){
struct node* ptr= (struct node*)malloc(sizeof(struct node));
struct node* p=head;
while(p->next!=NULL){
p=p->next;
}
ptr->data=data;
p->next=ptr;
ptr->next=NULL;
}
void linkedlisttraversal(struct node* ptr){
while(ptr!=NULL){
printf("%d ",ptr->data);
ptr=ptr->next;}
}
int main(){
struct node* head;
struct node* second;
struct node* third;
head=(struct node*)malloc(sizeof(struct node));
second=(struct node*)malloc(sizeof(struct node));
third=(struct node*)malloc(sizeof(struct node));
head->data=7;
head->next=second;
second->data=17;
second->next=third;
third->data=77;
third->next=NULL;
printf("initial value \n");
linkedlisttraversal(head);
//head=insertatfirst(48,head);
insertatindex(25,head,2);
insertatend(89,head);
head=insertafternode(26,second,head);
printf(" \nfinal value \n");
linkedlisttraversal(head);
}Editor is loading...