Answers for "linked list operations"

C++
0

linked list operations

// the function is returning the head of the singly linked list
Node insertAtEnd(Node head, int val)
{
    if( head == NULL ) // handing the special case
    {
        newNode = new Node(val)
        head = newNode
        return head
    }
    Node temp = head
    // traversing the list to get the last node
    while( temp.next != NULL )
    {
        temp = temp.next
    }
    newNode = new Node(val)
    temp.next = newNode
    return head
}
Posted by: Guest on April-28-2021
0

linked list operations

/* Given a Singly linked list L0->L1->L2->L3->L4->.......;Write a program to rearrange the nodes in the list so that the newly
    formed list is :L0->Ln->L1->Ln-1->L2->Ln-2->.....
    Sample input: 1 2 3 4 5 6
    Sample output:1 6 2 5 3 4
*/

#include<iostream>
using namespace std;
struct node
{
    int data;
    node* next;
};
node *head=new node;
node *head1,*head2;
void dummy(int s)
{
    node *temp=new node;
    temp->data=s;
    temp->next=NULL;
    head=temp;
}
void insert_ll(int k)//Inserting into the list
{
    node* temp=new node;
    temp->data=k;
    temp->next=NULL;
    if(head==NULL)
    {
        head=temp;
    }
    else
    {
        node* ptr=head;
        while(ptr->next!=NULL)
        {
            ptr=ptr->next;
        }
        ptr->next=temp;
    }
}
void split()//Splitting the list into two halves
{
    node* slow=head;
    node* fast=head->next;
    while(fast&&fast->next)
    {
        slow=slow->next;
        fast=fast->next->next;
    }
    head1=head;
    head2=slow->next;
    slow->next=NULL;
}
void reversing()//Reversing the list
{
    node* current=head2;
    node* prev=NULL;
    node*temp;
    while(current)
    {
        temp=current->next;
        current->next=prev;
        prev=current;
        current=temp;
    }
    head2=prev;
}
void merge__ll()//Merging the list
{
    dummy(0);
    node*current=head;
    while(head1||head2)
    {
        if(head1)
        {
            current->next=head1;
            current=current->next;
            head1=head1->next;
        }
        if(head2)
        {
            current->next=head2;
            current=current->next;
            head2=head2->next;
        }
    }
    head=head->next;
}
void print()//Printing the list
{
    node*temp =head;
    while(temp!=NULL)
    {
        cout<<temp->data<<" ";
        temp=temp->next;
    }
    cout<<endl;
}
int main()
{
    head=NULL;
    int n;
    cout<<"Enter the size:"<<endl;//for this question we will consider size though linked list is dynamic and does not have a fixed size
    cin>>n;
    int x;
    cout<<"enter the elements:"<<endl;
    for(int i=0;i<n;i++)
    {
        cin>>x;
        insert_ll(x);
    }
    cout<<"Linked list without the modification is:";
    print();
    split();
    reversing();
    merge__ll();
    print();
    return 0;
}
Posted by: Guest on July-22-2021

Browse Popular Code Answers by Language