2016-04-01 2 views
0

результат Пример:альтернативный слияния связанный список (с кодом)

Учитывая 2 связанный список:

ЛЛ1: 1 3 5 7 9

LL2: 2 4 6

После запуска программы результат должен быть ...

Результат:

ЛЛ1: 1 2 3 4 5 6 7 9

LL2: пусто

что-то не так с кодом ниже.

void alternateMergeLinkedList(LinkedList *ll1, LinkedList *ll2) 
{ 
    /* add your code here */ 
    int index = 1; 
    int j; 

    ListNode *ptr_node1; 
    ListNode *ptr_node2; 

    ptr_node1 = ll1->head; 
    ptr_node2 = ll2->head; 

    while (ptr_node2 != NULL) { 
     j = insertNode(ll1, index, ptr_node2->item); 
     j = removeNode(ll2, 0); 
     index += 2; 
    } 
} 

Учитывая insertNode и RemoveNode функции:

int insertNode(LinkedList *ll, int index, int value) 
{ 

    ListNode *pre, *cur; 

    if (ll == NULL || index < 0 || index > ll->size + 1) 
     return -1; 

    // If empty list or inserting first node, need to update head pointer 
    if (ll->head == NULL || index == 0) { 
     cur = ll->head; 
     ll->head = malloc(sizeof(ListNode)); 
     ll->head->item = value; 
     ll->head->next = cur; 
     ll->size++; 
     return 0; 
    } 

    // Find the nodes before and at the target position 
    // Create a new node and reconnect the links 
    if ((pre = findNode(ll, index - 1)) != NULL) { 
     cur = pre->next; 
     pre->next = malloc(sizeof(ListNode)); 
     pre->next->item = value; 
     pre->next->next = cur; 
     ll->size++; 
     return 0; 
    } 

    return -1; 
} 


int removeNode(LinkedList *ll, int index) 
{ 

    ListNode *pre, *cur; 

    // Highest index we can remove is size-1 
    if (ll == NULL || index < 0 || index >= ll->size) 
     return -1; 

    // If removing first node, need to update head pointer 
    if (index == 0) { 
     cur = ll->head->next; 
     free(ll->head); 
     ll->head = cur; 
     ll->size--; 

     return 0; 
    } 

    // Find the nodes before and after the target position 
    // Free the target node and reconnect the links 
    if ((pre = findNode(ll, index - 1)) != NULL) { 

     if (pre->next == NULL) 
      return -1; 

     cur = pre->next; 
     pre->next = cur->next; 
     free(cur); 
     ll->size--; 
     return 0; 
    } 

    return -1; 
} 
+0

Попробуйте выполнить код, построчно, в отладчике, чтобы увидеть, что он на самом деле делает. –

+0

Также в вашей функции 'alternateMergeLinkedList', что' index + = 2' может быть не так хорошо, когда 'll2' длиннее' ll1'. –

+0

Наконец, вы показали нам ожидаемый результат, но что такое * актуальные * результаты? Как вы получаете этот результат? Пожалуйста, [прочитайте о том, как задавать хорошие вопросы] (http://stackoverflow.com/help/how-to-ask), и узнайте, как создать [Минимальный, ** Полный ** и Подтверждаемый пример] (http: //stackoverflow.com/help/mcve). –

ответ

0

Вы устанавливаете ptr_node2 раз перед циклом, и это все. Если вы не обновите его в цикле, он не изменится.

Лучшее состояние цикла может быть while (ll2->size > 0).

+0

Спасибо. Это решает проблему бесконечного цикла. Однако результат не тот, которого мы ожидаем. вход: ЛЛ1: 1 3 5 LL2: 2 4 выход: ЛЛ1: 1 2 3 -572662307 5 LL2: Пустой Существует что-то не так с второй итерации. – Aung