加入链表中的两个编号列表

时间:2014-01-08 08:43:35

标签: c linked-list

NO *compare(NO *head1, NO *head2) {
    NO *temp = NULL;
    NO *tmp = NULL;
    NO *head = NULL;
    int i = 0;

    for (temp = head1; temp->next != NULL; temp = temp->next) {
        for (tmp = head2; tmp->next != NULL; tmp = tmp->next) {
            if (tmp->val <= temp->val) {
                head = new_node(tmp->val, i, head);
                i++;
            }
            printf("0");
        }
        head = new_node(temp->val, i , head);
        i++;
    }

    return head;
}

“该函数旨在采用两个已排序的链表并创建一个不重复的列表,并按升序排序”

2 个答案:

答案 0 :(得分:2)

存在逻辑错误。想一想

  1. 可能会添加很多次相同的节点。
  2. 可能根本没有任何元素。
  3. 尝试使用一个for循环来解决问题。即,当其中一个命中NULL时,遍历列表,检出哪个为null,并附加其他列表中的元素,这些元素在遇到null之前不为空。

    这个问题更像是组合数组来看看

      

    MERGE SORT

    尝试这个逻辑

          for(initialization; temp->link != NULL || tmp->link != NULL;)
          {
               // check which is greater
               // copy that into new list
              // accordingly increment that pointer(temp or tmp) 
          }
          if(temp->link == NULL)
          {
              // copy elements of second list till elements are remaining 
          }
          else if(tmp->link == NULL)
          {
               // copy the elements of first list till elements are remaining
          }
    

答案 1 :(得分:0)

NO *merge(NO *head1, NO *head2){
    NO *head = NULL;
    NO *current, *select;

    while(head1 != NULL || head2 != NULL){
        if(!head2 || head1 &&  head1->i < head2->i){
            select = head1;
            head1 = head1->nextp;
        } else if(!head1 || head2 && head2->i < head1->i){
            select = head2;
            head2 = head2->nextp;
        } else if(head1 && head2 && head1->i == head2->i){
            select = head1;
            head1 = head1->nextp;
            head2 = head2->nextp;
        }
        NO *new_node = malloc(sizeof(NO));
        new_node->val = select->val;
        //new_node->next = NULL;
        if(head==NULL){
            current = head = new_node;
        } else {
            current->next = new_node;
            current = current->next;
        }
    }
    current->next = NULL;
    return head;
}