Delete Alternate Nodes in LL

Implementation in C:
#include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node* next;
};
void push(struct node** ref, int newData)
{
    struct node* newNode = (struct node*)malloc(sizeof(struct node));
    newNode->data = newData;
    newNode->next = (*ref);
    (*ref) = newNode;
}
void print(struct node* n)
{
    struct node* temp = n;
    if(temp == NULL)
    {
    printf("Empty LinkedList");
    }
    while(temp!=NULL)
    {
    printf(" %d",temp->data);
    temp=temp->next;
    }
}
void alternateDelete(struct node* head)
{
    struct node* prev= head;
    struct node* node=head->next ;
    if(head == NULL)
        return;
    while(prev != NULL && node != NULL)
    {
    prev->next = node->next;
    free(node);
    prev= prev->next;
    if(prev!= NULL)
        node=prev->next;
    }
}
int main()
{
    struct node* head = NULL;
    push(&head,1);
    push(&head,2);
    push(&head,3);
    push(&head,4);
    push(&head,5);
    push(&head,6);
    push(&head,7);
    push(&head,8);
    print(head);
    alternateDelete(head);
    printf("\n");
    print(head);

}
Time Complexity:
O(n)

Comments

Popular posts from this blog

Three mislabeled Jar

Difference between Macro And function