2019-11-18 13:51

# C语言：合并有序双向链表问题

``````#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 */

{
int data;
};

// Function to insetail new node
{
p->data = key;
p->next = NULL;

// If first node to be insetailed in doubly
{
*tail = p;
return;
}
// If node to be insetailed has value less
// than first node
{
p->prior = NULL;
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.
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
{
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;
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]);
}
printList(La);
struct LinkList *Lb = NULL, *pb = NULL;
for(int i=5;i<10;i++)
{
nodeInsetail(&Lb, &pb,num[i]);
}
printList(Lb);
printf("\n");

pc=Lc;//备用合并链表起始地址
pa=La->next;
pb=Lb->next;                    （这里有问题！）
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:2 3 4 5 7 8 9 10请按任意键继续. . .

``````
• 写回答
• 好问题 提建议
• 追加酬金
• 关注问题
• 邀请回答

#### 1条回答默认 最新

• QiQaWgYu 2019-11-18 15:48
``````你这是不带头结点的链表，pa=La->next;pb=Lb->next; pa，pb指向的是第二个结点
``````
评论
解决 无用
打赏 举报