Insertionsort双链表

时间:2015-11-03 15:52:53

标签: c++ pointers doubly-linked-list insertion-sort

我试图为我的双链表创建一个insertionsort。问题是它陷入无限循环,我无法弄清楚原因。我对指针比较新,所以我必须要错过一些东西。

这是我用来排序的代码。

for (Node* i = m_Head; i != NULL; i = i->Next) {
    for (Node* j = i; j != m_Head;) {
        if (j->Prev == NULL)
        {
            break;
        }
        if (j->Value < j->Prev->Value)
        {
            Node* NP = j->Prev;
            Node* N = j;

            Node* NP_prev = NP->Prev;
            Node* NP_next = NP->Next;
            Node* N_Prev = N->Prev;
            Node* N_Next = N->Next;

            NP->Next = N_Next;
            NP->Prev = N;
            N->Next = NP;
            N->Prev = N_Prev;


            if (NP_prev == NULL)
            {
                std::cout << "NP is head, new head is now N" << std::endl;
                m_Head = N;
            } else {
                NP_prev->Next = N;
            }

            if (N_Next == NULL)
            {
                std::cout << "N is tail, new tail is now NP" << std::endl;
                m_Tail = NP;
            }   else {
                N_Next->Prev = NP;
            }


        }
        else {
            break;
        }
    }
}

如果我想排序例如列表5,3,7,0,2,9,其中5是头部,9是尾部,它将导致

  

3,5,7,7,0,7

     

3,5,0,0,0,0

     

3,5,7,7,0,7

     

3,5,0,0,0,0

反复循环。

节点类如下所示:

class Node{
private:

public:
    Node* Next = NULL;
    Node* Prev = NULL;
    int Value = 0;
};

0 个答案:

没有答案