#include<stdio.h>
#include<stdlib.h>
struct Node{
int data;
struct Node *next;
};
int size(struct Node* newNode){
int count=0;
while(newNode!=NULL){
newNode = newNode->next;
count++;
}
return count;
}
void push(struct Node** head1, int item){
struct Node* newNode = (struct Node*) malloc(sizeof(struct Node));
newNode->data = item;
newNode->next = *head1;
*head1 = newNode;
}
void delete(struct Node** head1, int position)
{
struct Node* tempData = *head1;
struct Node* prev;
//Deleting the head node if needed
int s = size(*head1);
if(position<1 || position>s){
printf("Invalid position\n");
return;
}
if(position==1)
{
*head1 = tempData->next;
free(tempData);
return;
}
while (--position)
{
prev = tempData;
tempData = tempData->next;
}
prev->next = tempData->next;
free(tempData);
}
void displayList(struct Node* newNode){
while(newNode!=NULL)
{
printf("%d->",newNode->data);
newNode = newNode->next;
}
printf("\n\n");
}
void DeleteNodes(struct Node* head1){
struct Node* head2 = head1;
int count=0;
int i = 1;
while(head1!=NULL){
int m = head1->data;
head1 = head1->next;
int n = head1->data;
head1 = head1->next;
if(m<n){
delete(head1,i);
}
printf("%d->",head1->data);
i++;
count++;
}
while(head2 != NULL){
printf("%d->",head2->data);
head2 = head2->next;
}
printf("\n\nCount is\t%d\n",count);
}
int main()
{
struct Node* head = NULL;
push(&head,9);
push(&head,5);
push(&head,1);
push(&head,2);
push(&head,7);
push(&head,9);
push(&head,4);
push(&head,5);
push(&head,2);
push(&head,6);
printf("\nSample input\n");
displayList(head);
printf("\nSample output\n");
DeleteNodes(head);
return 0;
}
Comments
Leave a comment