代码如下(希望对大家有帮助)
#include <iostream>
using namespace std ;
class Node{
public:
int data ;
Node *next ;
};
Node * createNode(int n ){
Node *head = new Node ;
Node *pre = head ;
for(int i = 0 ; i < n ; i++){
Node *p = new Node ;
cin>>p->data ;
pre->next = p ;
pre = p ;
p->next = NULL ;
}
return head ;
}
void display(Node *head){
Node *p = head->next ;
while(p != NULL){
cout<<p->data<<" " ;
p = p->next ;
}
}
Node* add(Node *node1, Node *node2){
Node*node;
Node*first , *second , *third ;
//将合并后的链表存在A表中
node= node1;
first = node1->next ;
second = node2->next ;
third = node;
while(first && second)
{
if(first->data< second->data)
{
third->next = first;
first = first->next;
third = third->next;
}
else if(first->data == second->data)
{
third->next = first ;
third = third->next ;
third = second->next ;
third = third->next ;
}
else
{
third->next = second ;
second = second->next ;
third = third->next ;
}
}
//将多余的接到third上
third->next=(first ? first : second) ;
return node;
}
int main(){
Node *p = createNode(5) ;
Node *q = createNode(3) ;
display(p) ;
cout<<"\n" ;
display(q) ;
cout<<"\n" ;
display(add(p , q)) ;
return 0 ;
}
运行结果: