swap in doubly linked list

后端 未结 2 728
臣服心动
臣服心动 2021-01-22 14:45

I am trying to swap two nodes in a doubly linked list. Below is the part of program having swap function.

 int swap (int x, int y)
{
    struct node *temp = NU         


        
2条回答
  •  借酒劲吻你
    2021-01-22 15:07

    This can be compacted, but if you are having problems, it can help to spell it out in detail.

    typedef struct node Node;
    
    void link( Node* a, Node* b )
    {
        a->next = b;
        b->prev = a;
    }
    
    void swap_nodes( Node* a, Node* b )
    {
        if(a==b) return; // don't swap with yourself
    
        // handle adjacent nodes separately
        if( a->next == b )
        {
            Node* bef = a->prev;
            Node* aft = b->next;
            link( bef, b);    // link bef, b, a, aft
            link( b, a );
            link( a, aft );
        }
        else if( b->next == a )
        {
            Node* bef = b->prev;
            Node* aft = a->next;
            link( bef, a);   // link bef, a, b, aft
            link( a, b );
            link( b, aft );
        }
        else
        {
            Node* a_prv = a->prev;
            Node* a_nxt = a->next;
            Node* b_prv = b->prev;
            Node* b_nxt = b->next;
    
            link( a_prv, b ); link( b, a_nxt ); // links b in a's old position
            link( b_prv, a ); link( a, b_nxt ); // links a in b's old position
        }
    }
    

    Also note that your head node should never be null, it should be a sentry node that links to itself if your list is empty. This means that there are never a first node, nor a last, nor is the list ever empty. This removes a ton of special cases. See here

提交回复
热议问题