合并2个已排序的链表未获得所需的输出

时间:2016-04-23 12:26:38

标签: data-structures merge linked-list

以下代码无效... 我试图使用迭代函数合并2个链表。 但它没有提供所需的输出..它是无限地打印元素 我正在学习编程.. 帮帮我... 提前谢谢......

#include<stdio.h>
#include<stdlib.h>


typedef struct Node
 {
   int data;
   struct Node *next;
 }list_node;



list_node* MergeLists(list_node *headA, list_node* headB)
{
  if (headA == NULL && headB == NULL) {
     return NULL;
  }

   if (headA == NULL) {
    return headB;
}

if (headB == NULL) {
    return headA;
}

if (headA->data > headB->data) {
    list_node *tmp = headB;
    headB = headA;
    headA = tmp;
}

list_node *listHead = headA;

while (headB) {

    while (headA->next != NULL &&
           headB->data > headA->next->data) {
        headA = headA->next;
    }


    list_node* nextB = headB->next;
    headB->next = headA->next;
    headA->next = headB;
    headB = nextB;
   }

    return listHead;
}

 list_node* push(list_node* head_r, int new_data)
  {
    list_node* new_Node = (list_node*)malloc(sizeof(list_node));

    new_Node->data  = new_data;
    new_Node->next = head_r;
    head_r = new_Node;
    return head_r;
  }

void Print(list_node* head_r)
{
   while(head_r)
    {
      printf("%d\n", head_r->data);
      head_r = head_r->next;
    }


 }

 int main()
 {

   list_node* l_list = NULL;
   list_node* l_list2 = NULL;
   l_list = push(push(push(push( push(l_list, 1),2),3),4),5);
   l_list2 = push(push(push(push( push(l_list, 6),8),3),4),0);
   MergeLists(l_list, l_list2);
   printf("Merge 2 Sorted list \n");
   Print(l_list);
   return 0;

 }

2 个答案:

答案 0 :(得分:1)

你在这一行上有一个拼写错误l_list2 = push(push(push(push( push(l_list, 6),8),3),4),0); 我认为它应该是l_list2 = push(push(push(push( push(l_list2, 6),8),3),4),0);

发生的事情是你现在有2个变量指向同一个列表。然后,当您执行合并时,尝试将列表合并到自身中。因为随着合并算法的每一步,你的列表变得更大,它永远不会完成。

答案 1 :(得分:0)

if (headA->data > headB->data) {
        list_node *tmp = headB;
        headB = headA;
        headA = tmp;
    }

应该是

if (headA->data > headB->data) {
        list_node *tmp = headB;
        headB = headA;
        headA = *tmp; //tmp is a pointer
    }

并在

l_list2 = push(push(push(push( push(l_list, 6),8),3),4),0); 

应该是

l_list2 = push(push(push(push( push(l_list2, 6),8),3),4),0); //l_list2