#recursively shift a linked list

25 messages · Page 1 of 1 (latest)

limber patio
#

I am trying to figure out how to recursively shift a linked list right once. I feel like I'm on the right track, but I can't seem to fully solve it.
Here is my code currently:

struct node *shift(struct node *node, struct node *head) {
    if (node == NULL || node->next == NULL) {
        return node;
    }

    if (node->next->next == NULL) {
        struct node *temp = node->next;
        temp->next = head; 
        node->next = NULL; 
        return temp; 
    }

    node->next = listShift(node->next, head);
    return temp;
}

I was hoping to try and do it without using the extra head parameter in the function, but I thought I'd try and figure it out with the extra parameter first.

eternal birchBOT
#

When your question is answered use !solved to mark the question as resolved.

Remember to ask specific questions, provide necessary details, and reduce your question to its simplest form. For tips on how to ask a good question use !howto ask.

limber patio
#

right now my list gets circularly linked back to itself and I can't quite figure out why

icy zodiac
#

Try debugging.

gentle veldt
#

What does shift mean exactly?

#

Like, add a new node at the beginning?

#

Aaaahh or cyclically shift, i.e. move the last node to the beginning? 🤔

limber patio
#

so i want the last node to become the first and the 2nd last to become the last

gentle veldt
#

Are you forced to use recursion?

limber patio
#

yes, with no while loops

#

i can do it easily enough with while loops but i just can't seem to get my head around recursion properly

gentle veldt
#

Hmm I think the last 2 lines are the problem

#

Should be just return listShift(...)

limber patio
#

tysm, that worked

#

whats the reason why this works and not my way?

gentle veldt
#

Well to shift, only 3 pointer reassignments are needed: set penultimate node's next to null, last node's next to head, and set head to be the last node.

All these are done in the if block.

So the assignment after the if block: node->next = listShift(...) looked kind of sus

limber patio
#

ok ty

#

so because I did everything i needed to do inside the if statement I don't want to be changing anything outside it?

gentle veldt
#

Well yes

#

You only need to change something when you've found the last node

#

Which is handled in your if block

limber patio
#

ok thanks, i think i understand

#

i'll work on removing the head parameter now

#

!solved