早教吧作业答案频道 -->其他-->
数据结构有序链表问题。Writeafunctiontomergetwosortedlinkedlists.Theinputlistshavetheirelementsinsortedorder,fromlowesttohighest.Theoutputlistshouldalsobesortedfromlowesttohighest.Youralgorithmshouldruni
题目详情
数据结构有序链表问题。
Write a function to merge two sorted linked lists. The input lists have their elements in sorted order, from lowest to highest. The output list should also be sorted from lowest to highest. Your algorithm should run in linear time on the length of the output list.
Write a function to merge two sorted linked lists. The input lists have their elements in sorted order, from lowest to highest. The output list should also be sorted from lowest to highest. Your algorithm should run in linear time on the length of the output list.
▼优质解答
答案和解析
typedef struct node
{
datatype data;
struct node *next;
node(int _data = 0, node *_next = NULL) : data(_data), next(_next) { }
}Node, *PNode, LinkedList, *PLinkedList;
PLinkedList Merge(PLinkedList &A, PLinkedList &B)
{
PNode C = new Node( );
PNode last = C;
PNode p = A->next, q = B->next;
while(p && q)
{
if(p->data < q->data)
{
last->next = p;
last = p;
p = p->next;
}
else
{
last->next = q;
last = q;
q = q->next;
}
}
if(p) last->next = p;
if(q) last->next = q;
delete A;
A = NULL;
delete B;
B = NULL;
return C;
}
{
datatype data;
struct node *next;
node(int _data = 0, node *_next = NULL) : data(_data), next(_next) { }
}Node, *PNode, LinkedList, *PLinkedList;
PLinkedList Merge(PLinkedList &A, PLinkedList &B)
{
PNode C = new Node( );
PNode last = C;
PNode p = A->next, q = B->next;
while(p && q)
{
if(p->data < q->data)
{
last->next = p;
last = p;
p = p->next;
}
else
{
last->next = q;
last = q;
q = q->next;
}
}
if(p) last->next = p;
if(q) last->next = q;
delete A;
A = NULL;
delete B;
B = NULL;
return C;
}
看了 数据结构有序链表问题。Wri...的网友还看了以下:
下列关于数据排序的说法中,错误的是()A.Word2000可以对表格中的数据自动排序B.Power 2020-05-23 …
数据库具有数据结构化、最小的冗余度和较高的( )。A.程序与数据可靠性B.程序与数据完整性C.程序与 2020-05-23 …
数据库具有数据结构化、最小冗余度和较高的()。A.程序与数据可靠性B.程序与数据完整性C.程序与数据 2020-05-24 …
某数据表降序排序某数据表中有5条记录,其中"编号"为文本型字段,其值分别为:129、97、75、1 2020-06-30 …
java中怎样实现数据排序.有一行数字,其中每三个为一组,再把这一行的前面27个和后面27个数字分 2020-07-17 …
数据结构有序链表问题。Writeafunctiontomergetwosortedlinkedli 2020-07-21 …
向函数高手求救有两组数据,分甲、乙两组,甲乙两组数据顺序不同,不能用排序,甲表和乙表都有一组相同的数 2020-11-03 …
关于表格排序的说法正确的是(请进!)关于表格排序的说法正确的是A只有数字类型可以作为排序的依据B只有 2020-12-05 …
当采用分块查找时,数据的组织方式为()当采用分块查找时,数据的组织方式为?A数据分成若干块,每块内数 2020-12-05 …
怎样用链表的方法解决基于有序顺序的二分法查找数据?如3212//3表示要查找的元素,2表示一共有2个 2020-12-05 …