此处大多数代码参考另一篇博文《动态单向链表的创建》,用以创建测试用的单链表。 #include <iostream> using namespace std; struct Node { int data; Node *next; }; Node *createList (Node *head) { struct Node *p, *s; int ch; cout << "Input a number,then press Enter. press Ctrl + Z to end input:" <<endl; while ((cin >> ch) && ch != EOF) { s = new Node; s->data = ch; if (head == NULL) { head = s; p = s; } else p->next = s; s -> next = NULL; p = s; } cin.clear(); //一次创建完成后,须清空输入缓冲区。这样做之后,多次调用该函数,创建多个链表时才不会出错 return head; } void showList (Node *head) { do { cout << head->data << ' '; head = head->next; }while (head != NULL); } //递归方法实现将两个有序的单链表合并成一个有序单链表 Node *mergeList(Node *h1, Node *h2) { Node *h = NULL; if(h1 == NULL) return h2; if(h2 == NULL) return h1; if(h1->data < h2->data) { h = h1; h->next = mergeList(h1->next, h2); } else { h = h2; h->next = mergeList(h1, h2->next); } return h; } int main() { Node *head = NULL, *head1 = NULL, *head2 = NULL; head1 = createList(head1); head2 = createList(head2); head = mergeList(head1, head2); showList(head); return 0; }