Friday, January 29, 2021

Move last element of LL to front

 Approach: 

1. Traverse the list till last node.

2. Take 2 pointers: one to store the address/ pointer of last node and other to store the pointer/address of 2nd last node.

3. After the loop is executed, do the following operation:

a) Make second last node as last node of list(seclast->next=NULL)

b) Set next of last node as head(last->next=*head_ref)

c) Make last node as head node(*head_ref= last) 


Code

class node{}

void movetofront(node **head_ref)

{

    //do nothing if list is empty or contain only 1          node

    if(*head_ref==NULL || 

    (*head)- >next==NULL) 

    return;


     //initialize 2nd and last pointers

     node *seclast=NULL; 

     node *last=*head_ref;

     

     

 //after loop seclast pointer stores address of   seclast node and last stores the address of last   node

  while(last->next!=NULL)    

 {

  seclast=last; last=last->next;

  }  //while ends  


//set next of secalst as NULL

seclast->next=NULL; 

last->next= (*head_ref); //set last node pointer point to headnode

(*head_re)f= last;

} //function ends


void push(struct node** head_ref, int new_data) {}

void printlist(node* head) {}

int main() {}




0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home