2015-07-11 106 views
0

我想插入一个元素排序的循环双向链表,,这里是我的尝试:插入元件插入排序的循环双向链表

void insertSorted(Node *&head,int x){ 
    Node *temp = new Node(); 
    temp->data = x; 
    temp->next = temp; 
    temp->prev = temp; 

    if(head == NULL){ 
     head = temp; 
     return; 
    } 

    Node *p = head; 
    Node *q = NULL; 
    do{ 
     q = p; 
     p=p->next; 
    }while(p != head && x>p->data); 

    if(q == NULL){ 
     temp->next = head; 
     head->prev = temp; 
     head = temp; 
    } 
    else { 
     q->next = temp; 
     if(p!=NULL){ 
      temp->next = p; 
      p->prev = temp; 
     } 
     temp->prev = q; 
    } 
} 

代码工作,但问题是与第一元素每次它没有排序,,,例子插入10 9 8 1 2 ,,,输出将是10 1 2 8 9 ,,它应该是1 2 8 9 10

+1

听起来像你应该做一些调试。 –

+0

该列表是正确的。它是循环的,所以10开始或结束,取决于你开始打印的位置。所以我会说'head'不是指向你想要的节点。调试器将帮助您了解这一点。 – user3386109

+0

你忘了更新'head'。够了吗?还是需要进一步的帮助? – Beta

回答

0

if(q == NULL)永远不会发生你的代码。所以,这里出现问题。

当你遇到第一个节点的问题时,条件应该是(q == head)并更新头部。你的代码是否正确。

+0

非常感谢,我没有看到:D我需要睡觉:D – Saidar