Swap nodes in a singly-linked list

前端 未结 3 1774
予麋鹿
予麋鹿 2020-11-30 09:34

I am trying to swap two nodes. For example if the nodes are a and b I am passing the pointers
(a-1)->next and (b-1)->n

3条回答
  •  温柔的废话
    2020-11-30 10:07

    I was hoping for cut-and-paste code, but didn't find it. If anyone is still interested, this is the answer. I did the brute force analysis of all 3 cases.

    // swaps nodes at locations *sp and *tp
    struct stack *s = *sp; // store locations to prevent overwritten bugs
    struct stack *t = *tp;
    if(&t->next == sp) { // order u (tp)-> t (sp)-> s -> ...
        t->next = s->next;
        s->next = t;
        *tp = s;
    } else if(&s->next == tp) { // order u (sp)-> s (tp)-> t -> ...
        s->next = t->next;
        t->next = s;
        *sp = t;
    } else { // disconnected u (sp)->s -> ..., v (tp)->t -> ...
        struct stack *next = s->next;
        s->next = t->next;
        t->next = next;
        *sp = t;
        *tp = s;
    }             
    // If you track the end of your list, it be the one pointing to NULL.                                           
    if(s->next == NULL) {                                  
        end = &s->next;                                 
    } else if(t->next == NULL) {                           
        end = &t->next;                                 
    }
    

    Note: This code works if sp == tp, but assumes you don't have the pathological case where BOTH &s->next == tp && &t->next == sp (starting with cycle).

提交回复
热议问题