Saturday, December 4, 2021
HomeTop Coding QuestionWrite a program to reverse a linkedlist.

Write a program to reverse a linkedlist.

Given a linkedlist ,we have to make program to reverse node of a linkedlist .

Example:

Input:1 2 3 4 5 6
Output:6 5 4 3 2 1

Logic:

STEP 1:start traversing a node of linkedlist till reach  the end of linkedlist.
STEP 2:initalise three pointer current,previous ,next.
STEP 3:start traversing next node before traversing next node it will store the address to previous node.

Code

void ReverseLinkedlist()
{
    if(head==NULL)
    {
        return;
    }
    int count=0;
    Node *cur=head;
    Node *prev=NULL;
    Node *nxt=NULL;
    while(cur!=NULL)
    {
        
        nxt=cur->nxt;
        cur->nxt=prev;
        prev=cur;
        cur=next;
    }
   head=prev;
  
}

Ouput:

1 2 3 4 5 6
6 5 4 3 2 1

Time Complexity:O(N)

Space Complexity:O(1)

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -

Most Popular

Recent Comments