好的,下面是问题:
你有两个已经排序好的列表,你需要将它们合并并返回一个新的列表,而且不需要创建任何新的额外节点。返回的列表也应该是有序的。
方法签名为:
Node* MergeLists(Node* list1, Node* list2);
struct Node{
int data;
Node *next;
}
以下是我想出的解决方案,Node* MergeLists(Node* list1, Node* list2){
Node* mergedList;
if(list1 == null && list2 ==null){//if both are null, return null
return null;
}
if(list1 == null){//if list1 is null, simply return list2
return list2;
}
if(list2 == null){//if list2 is null, simply return list1
return list1;
}
if(list1.data < list2.data){//initialize mergedList pointer to list1 if list1's data is lesser
mergedList = list1;
}else{//initialize mergedList pointer to list2 if list2's data is lesser or equal
mergedList = list2;
}
while(list1!=null && list2!=null){
if(list1.data < list2.data){
mergedList->next = list1;
list1 = list1->next;
}else{
mergedList->next = list2;
list2 = list2->next;
}
}
if(list1 == null){//remaining nodes of list2 appended to mergedList when list1 has reached its end.
mergedList->next = list2;
}else{//remaining nodes of list1 appended to mergedList when list2 has reached its end
mergedList->next = list1;
}
return mergedList;
}
我非常有信心这可以得到改进。请帮我找出哪些行是我冗余添加的。请随意批评我的语法错误和逻辑。
谢谢!