Search code examples
linked-listruntime-error

Getting run-time error for 'rotate the doubly linked list'


I am posting this question because i am getting run-time error for any linked list problem that i code. There must be a generic mistake that I must be doing. Please help me figure out what's that mistake

This is just one of those problems: https://practice.geeksforgeeks.org/problems/rotate-doubly-linked-list-by-p-nodes/1

Here is my solution:(I was only supposed to complete the function)

struct node*update(struct node* start,int p)

{
//Add your code here
node *last=start,*nxt,*i=start;
int n=1;;
while(last!=NULL){
    last=last->next;
    n+=1;
}
cout<<last->data<<"\n";
p=p%n;
for(int i=0;i<p;i++){
    nxt=start->next;
    last->next=start;
    start->next=NULL;
    start->prev=last;
    nxt->prev=NULL;
    last=last->next;
    start=nxt;
}
return start;

}


Please let me know what is wrong with this code.

Thank you in advance


Solution

  • So , you're trying your hands on linked-lists ,that's great .

    Linked list is like a game , a 'game of pointers' . You seems to very good in the 'game of logics' while you lack just a few things in ' pointers game'.

    Going through your mentioned statement- " i am getting run-time error for any linked list problem that i code.", I would suggest you to learn how to debug your code and how self testing of code is done .

    Coming back to your code , you are traversing the whole list to get access of the last node . To achieve that goal - you have used while loop . But look what conditional statement you've used in that , and what you'll be left with after execution of while loop .

    node *last=start,*nxt,*i=start;
    int n=1;;
    while(last!=NULL){
        last=last->next;
        n+=1;
    }
    

    At first try to check you code for a linked list of size 2 or 3 only.

    Isn't your code giving the value of n as [size(of linked-list) +1] and you are left with last pointer pointing to NULL. So how will you be able to get last->data when last is NULL.

    Just a simple mishandling of pointers . Otherwise the logic of your later code part is fine .

    Modification needed

    Last node is the one , whose next is pointing to NULL . So run your loop till that node only .

    int n=1;;
    while(last->next!=NULL){ //last->next instead of last
        last=last->next;
        n+=1;
    }
    

    Hope this will help .

    Keep asking , keep growing :)