C ++,指针,两个排序的链表的合并

时间:2018-06-20 13:07:37

标签: c++11 pointers debugging merge linked-list

我引用了GeeksForGeeks中的代码来合并两个排序的链表。

#include <bits/stdc++.h>
using namespace std;

/* Link list node */
struct Node
{
    int data;
    struct Node* next;
};

void MoveNode(Node **destRef, Node **sourceRef){
    cout << "pp: " << (*sourceRef) << endl;
    Node *tempNode = *sourceRef;

    cout << "tt:" << tempNode->next << endl;
    *sourceRef = tempNode->next;

    tempNode->next = *destRef;

    *destRef = tempNode;
    cout << "qq: " << (*sourceRef) << endl;

}

struct Node* SortedMerge(Node *a, Node *b){
    Node *dummy;
    Node *tail;
    dummy->next = NULL;
    tail = dummy;
    cout << "hii" << endl;

    while(true){
        if(a==NULL){
            cout << "aa" << endl;
            tail->next = b;
            break;
        }
        else if(b==NULL){
            cout << "bb" << endl;
            tail->next = a;
            break;
        }

        if(a->data < b->data){
            cout << "cc" << endl;
            MoveNode(&(tail->next), &a);
            tail = tail->next;
        }
        else if(a->data >= b->data){
            cout << "dd" << endl;
            // cout << "b->data: " << b << endl;
            MoveNode(&(tail->next), &b);
            // b = b->next;
            // cout << "b->data: " << b << endl;
            // cout << "b->data: " << b->data << endl;
            tail = tail->next;
        }
    }
    return dummy->next;
}


/* Function to insert a node at the beginning of the
   linked list */
void push(struct Node** head_ref, int new_data)
{
    /* allocate node */
    struct Node* new_node =
        (struct Node*) malloc(sizeof(struct Node));

    /* put in the data  */
    new_node->data  = new_data;

    /* link the old list off the new node */
    new_node->next = (*head_ref);

    /* move the head to point to the new node */
    (*head_ref)    = new_node;
}

/* Function to print nodes in a given linked list */
void printList(struct Node *node)
{
    while (node!=NULL)
    {
        printf("%d ", node->data);
        node = node->next;
    }
    cout << endl;
}

/* Drier program to test above functions*/
int main()
{
    /* Start with the empty list */
    struct Node* res = NULL;
    struct Node* a = NULL;
    struct Node* b = NULL;

    /* Let us create two sorted linked lists to test
      the functions
       Created lists, a: 5->10->15,  b: 2->3->20 */
    push(&a, 15);
    push(&a, 10);
    push(&a, 5);

    push(&b, 20);
    push(&b, 3);
    push(&b, 2);

    /* Remove duplicates from linked list */
    res = SortedMerge(a, b);

    printf("Merged Linked List is: \n");
    printList(res);

    return 0;
}

对于主函数中的给定示例,如果我未在第二次打印节点值(如果在SortedMerge函数中进行while循环),则程序输出错误。如果我确实打印它们,程序将提供正确的输出。我觉得很奇怪。有人可以帮我吗?

0 个答案:

没有答案