Closed. This question is off-topic。它当前不接受答案。
                            
                        
                    
                
                            
                                
                
                        
                            
                        
                    
                        
                            想改善这个问题吗? Update the question,因此它是on-topic,用于堆栈溢出。
                        
                        3年前关闭。
                                                                                            
                
        
样本结果:

给出2个链表:


  LL1:1 3 5 7 9
  
  LL2:2 4 6


运行程序后,结果应为...

结果:


  LL1: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;
}

最佳答案

您只需在循环之前设置ptr_node2即可。如果您在循环中不进行更新,则不会更改。

更好的循环条件可能是while (ll2->size > 0)

09-27 04:50