Swapping nodes in a linked list

前端 未结 5 1550
逝去的感伤
逝去的感伤 2020-12-20 06:04

I am trying to swap two adjacent nodes in a linked list, and I think I understand the idea of how to do it using a temporary node.

Here is my struct swap function

5条回答
  •  误落风尘
    2020-12-20 06:57

    Ignore the answers about doubly-linked lists. To answer your question, you need to think about how you call your function.

    Right now, you have a function that takes a pointer to a pointer. It currently points to a node (node A), which in turn points to another node (node B). Imagine this scenario:

    partType a, b, c, d;
    a->next = &b;
    b->next = &c;
    c->next = &d;
    d->next = NULL;
    

    Now, you want to swap the order of B and C to have A->C->B->D using your function. Well, you'd do:

    swap_node(&a->next);
    

    A was pointing to B; now it's pointing to C. As you can see, the "previous" node is already pointing to C, as you expected. In other words, you've already accomplished your goal. Cheers!

    Notes: What exactly is happening in your swap function? Let's break it down. First, the parameter you give it is a pointer to a pointer. Those are a bitch to think about because of the wording -- don't let the wording fool you. Just like "rate of change of the rate of change" is a bitch to think about but "acceleration" is much easier. You want to parse it by remembering that the parameter is, first and foremost, a pointer to some data, and your function is going to modify the data that it points to.

    So your function gets a pointer to this 'p', which is pointing to a spot in the linked list which (you assume, see PS) points to two nodes (call them X and Y). Diagram:

    [p] --> X[next] --> Y[next] --> Z[next]
    

    Your algorithm does:

    1. Make [p] point to Y: *item = (*item)->next
    2. Make X[next] point to Z: temp->next = (*item)->next
    3. Make Y[next] point to X: (*item)->next = temp

    So, if you now consider my A, B, C, D example, the linked list was:

    A[next] --> B[next] --> C[next] --> D[next] --> NULL
    

    you can see more clearly what pointer I'm passing. It's the location in memory (read: pointer) where A[next] is stored, which your function needs to do the swapping.

    Incidentally, another way to code this would be to do:

    a->next = swap_node(&a->next);
    

    but don't do that. It's redundant.

    PS Have you thought about what happens when you ask to swap the last node in the series? Right now, things explode :P

提交回复
热议问题