Skip to main content

Linked List Implementation Using C

 Linked List Implementation Using C


#include<stdio.h>
#include<stdlib.h>
struct node{
    int data;
    struct node *next;
};
struct node *addEnd(struct node *head,int data)
{
    struct node *temp;
    temp = (struct node*)malloc(sizeof(struct node));
    temp->data = data;
    temp->next = NULL;
    if(head==NULL)
    {
        head=temp;
        head->next=NULL;
    }
    else{
        struct node *ptr = head;
        while(ptr->next!=NULL)
        {
            ptr=ptr->next;
        }
        ptr->next=temp;
    }
    return head;
}
struct node *addBegin(struct node *head,int data)
{
    struct node *temp;
    temp = (struct node*)malloc(sizeof(struct node));
    temp->data=data;
    temp->next=NULL;
    if(head==NULL)
    {
        head=temp;
    }
    else{
        temp->next=head;
        head=temp;
    }
    return head;
}
void display(struct node* head)
{
    printf("The elements in linked list are:\n");
    while(head!=NULL)
    {
        printf("%d\n",head->data);
        head=head->next;
    }
}
struct node *merge(struct node *head,struct node *list)
{
  if(head==NULL)
  {
    head=list;
  }
  else {
    struct node *ptr = head;
    while(ptr->next!=NULL)
    {
      ptr=ptr->next;
    }
    ptr->next=list;
  }
  return head;
}
int main()
{
    struct node *head = NULL;
    head = addBegin(head, 10);
    head = addEnd(head, 20);
    head = addEnd(head, 30);
    head = addEnd(head, 40);
    struct node *list = NULL;
    list = addBegin(list, 50);
    list = addEnd(list, 60);
    list = addEnd(list, 70);
    list = addEnd(list, 80);
    head = merge(head, list);
    display(head);
    return 0;
}

Popular posts from this blog