从txt文件中读取5 4 2 3 1 10 6 8 7 9 到数组中,建立了两个递增排序的双向链表,内容分别为 1 2 3 4 5和6 7 8 9 10,现在想将两个链表合并输出一个递增的双向链表,但是!输出的链表少了1 和 6 两个数字,麻烦大佬看一下合并时哪里出了问题
#include "stdafx.h"
#include <stdlib.h>
#include <string.h>
#include <iostream>
using namespace std;
#include<fstream>
#include<stdio.h>
/* C program to insetail nodes in doubly
linked list such that list remains in
ascending order on printing from left
to right */
struct LinkList // A linked list node
{
int data;
struct LinkList *prior;
struct LinkList *next;
};
// Function to insetail new node
void nodeInsetail(struct LinkList **head, struct LinkList **tail, int key)
{
struct LinkList *p = new LinkList;
p->data = key;
p->next = NULL;
// If first node to be insetailed in doubly
// linked list
if (*head == NULL)
{
*head = p;
*tail = p;
(*head)->prior = NULL;
return;
}
// If node to be insetailed has value less
// than first node
if ((p->data) < ((*head)->data))
{
p->prior = NULL;
(*head)->prior = p;
p->next = (*head);
(*head) = p;
return;
}
// If node to be insetailed has value more
// than last node
if ((p->data) > ((*tail)->data))
{
p->prior = (*tail);
(*tail)->next = p;
(*tail) = p;
return;
}
// Find the node before which we need to
// insert p.
LinkList *temp = (*head)->next;
while ((temp->data) < (p->data))
temp = temp->next;
// Insert new node before temp
(temp->prior)->next = p;
p->prior = temp->prior;
temp->prior = p;
p->next = temp;
}
// Function to print nodes in from left to right
void printList(struct LinkList *temp)
{
while (temp != NULL)
{
printf("%d ", temp->data);
temp = temp->next;
}
}
// Driver program to test above functions
int main()
{
int num[10],i,j=0;
int datalen=0;
ifstream file("linklist.txt");
while( ! file.eof() )
file>>num[datalen++];
file.close();
struct LinkList *La = NULL, *pa = NULL;
for(int i=0;i<5;i++)
{
nodeInsetail(&La, &pa,num[i]);
}
printf("\nDoubly linked listA on printing:");
printList(La);
struct LinkList *Lb = NULL, *pb = NULL;
for(int i=5;i<10;i++)
{
nodeInsetail(&Lb, &pb,num[i]);
}
printf("\nDoubly linked listB on printing:");
printList(Lb);
printf("\n");
struct LinkList *Lc=NULL;//头
struct LinkList *pc=NULL;//备用地址
struct LinkList *q=NULL;
Lc=(struct LinkList*)malloc(sizeof(struct LinkList));
pc=Lc;//备用合并链表起始地址
pa=La;
pb=Lb; (这里有问题!)
while(pa&&pb)
{
if(pa->data<pb->data)
{
Lc->next=pa;
pa->prior=Lc;
pa=pa->next;
Lc=Lc->next;
}
else if(pa->data==pb->data)
{
Lc->next=pa;
pa->prior=Lc;
Lc=pa;
pa=pa->next;
q=pb->next;
free(pb);
pb=q;
}
else if(pa->data>pb->data)
{
Lc->next=pb;
pb->prior=Lc;
pb=pb->next;
Lc=Lc->next;
}
}
Lc->next=pa?pa:pb;
free(Lb);
printf("the result is:");
pa=pc->next;
while(pa)
{
printf("%d ",pa->data);
pa=pa->next;
}
return 0;
}
执行结果如下(工作停止)
Doubly linked listA on printing:1 2 3 4 5
Doubly linked listB on printing:6 7 8 9 10
the result is:1 2 3 4 5 -572662307 请按任意键继续. . .
之前写的是pa=La->next;
pb=Lb->next; 总是少了1 和 6