合并列表

时间:2019-04-20 05:33:14

标签: c++ data-structures linked-list

在以下代码中,我尝试替代合并2个列表,而不是以相反的顺序打印它们。但是我的代码没有给出正确的输出,它只是合并了第二个列表的最后一个元素。 输入:

1

3

1 3 5

3

2 4 6

实际输出: 5 6 3 1

预期输出: 5 6 3 4 1 2

有人可以告诉我代码中的问题吗?...

#include<bits/stdc++.h>
using namespace std;
struct Node
{
    int data;
    struct Node *next;
};
void push(struct Node ** head_ref, int new_data)
{
    struct Node* new_node = (struct Node*) malloc(sizeof(struct Node));
    new_node->data = new_data;
    new_node->next = (*head_ref);
    (*head_ref) = new_node;
}
void printList(struct Node *head)
{
    struct Node *temp = head;
    while (temp != NULL)
    {
        cout<<temp->data<<' ';
        temp = temp->next;
    }
    cout<<' ';
}
void mergeList(struct Node **head1, struct Node **head2);

int main()
{
    int T;
    cin>>T;
    while(T--){
        int n1, n2, tmp;
        struct Node *a = NULL;
        struct Node *b = NULL;
        cin>>n1;
        while(n1--){
            cin>>tmp;
            push(&a, tmp);
        }
        cin>>n2;
        while(n2--){
            cin>>tmp;
            push(&b, tmp);
        }
        mergeList(&a, &b);
        printList(a);
        printList(b);
    }
    return 0;
}

void mergeList(struct Node **p, struct Node **q)
{
     struct Node*temp1=*p,*temp2=*q,*t1,*t2;
     while(temp1!=NULL)
     {
         if(temp2==NULL)
            break;
         t1=temp1->next;
         t2=temp2;
         temp1->next=t2;
         t2->next=t1;
         temp1=t1;
         *q=temp2->next;
         temp2=*q;
     }
 }

1 个答案:

答案 0 :(得分:1)

说实话,我真的不确定您在mergeList函数中到底在做什么。该代码是非常有害的,因此我没有冒犯验证正确性的自由。我已重命名了几个变量并重新编写了代码,因此您可以以此为参考点,看看代码有什么问题。

    void mergeList(struct Node **p, struct Node **q)
    {
     struct Node *a = *p, *b = *q, *next_a, *next_b;
     while(a != NULL)
     {
         if(b == NULL)
            break;

         next_a = a->next;
         a->next = b;
         next_b = b->next;
         b->next = next_a;
         a = next_a;
         b = next_b;

     }
 }

希望这会有所帮助。干杯。

相关问题