I am trying to insert an element at second last place of my linked list...Please help me out I have created a function to enumerate the linked list with values 1,2,3...etc Then I have a function to insert at second last, and then I have a function to display the list.
#include <stdio.h>
#include<stdlib.h>
struct node{
int data;
struct node *next;
}*head=NULL;
void insert(int x){
int i = 1;
struct node *temp,*temp2=head;
while(x>0){
x--;
temp = (struct node*)malloc(sizeof(struct node));
head->data=i++;
head->next=temp;
head=temp;
}
head->next=NULL;
head=temp2;
}
void insertSecondLast(int x){
struct node *prev,*insert,*temp=head;
insert = (struct node*)malloc(sizeof(struct node));
insert->data=x;
while(head->next!=NULL){
prev = head;
head=head->next;
}
prev->next=insert;
insert->next=head;
head=temp;
}
void display(){
printf("\n[");
while(head->next!=NULL){
printf("%d, ",head->data);
head=head->next;
}
printf("NULL]");
}
int main(void) {
insert(4);
insertSecondLast(100);
display();
return 0;
}
headthe first time you encounterhead->data=i++;?displayfunctions should bewhile(head) { printf("%d, ", head->data); head = head->next; }