演算法單連結串列交換任意兩個元素

dongyu2013發表於2014-04-15
先一次遍歷找到這兩個元素curr1和curr2,同時儲存這兩個元素的前驅元素pre1和pre2。
然後大換血
public static Link SwitchPoints(Link head, Link p, Link q)
{
    if (p == head || q == head)
        throw new Exception(“No exchange with head”);
    if (p == q)
        return head;
    //find p and q in the link
    Link curr = head;
    Link curr1 = p;
    Link curr2 = q;
    Link pre1 = null;
    Link pre2 = null;

    int count = 0;
    while (curr != null)
    {
        if (curr.Next == p)
        {
            pre1 = curr;
            count++;
            if (count == 2)
                break;
        }
        else if (curr.Next == q)
        {
            pre2 = curr;
            count++;
            if (count == 2)
                break;
        }
        curr = curr.Next;
    }
    curr = curr1.Next;
    pre1.Next = curr2;
    curr1.Next = curr2.Next;
    pre2.Next = curr1;
    curr2.Next = curr;
    return head;
}
注意特例,如果相同元素,就沒有必要交換;如果有一個是表頭,就不交換。

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/29012686/viewspace-1142634/,如需轉載,請註明出處,否則將追究法律責任。

相關文章