创建2个递增的带头节点的有序链表,链表内容由键盘输入,并输出表内容
时间: 2023-07-10 13:25:03 浏览: 42
好的,下面是实现该功能的C++代码:
```c++
#include <iostream>
using namespace std;
struct ListNode {
int val;
ListNode* next;
ListNode(int x) : val(x), next(NULL) {}
};
ListNode* createList() {
ListNode* head = new ListNode(-1);
ListNode* cur = head;
int x;
while (cin >> x && x != -1) {
ListNode* temp = new ListNode(x);
cur->next = temp;
cur = cur->next;
}
return head->next;
}
void printList(ListNode* head) {
while (head) {
cout << head->val << " ";
head = head->next;
}
cout << endl;
}
int main() {
cout << "Please input the first sorted list (end with -1): ";
ListNode* l1 = createList();
cout << "Please input the second sorted list (end with -1): ";
ListNode* l2 = createList();
cout << "List 1: ";
printList(l1);
cout << "List 2: ";
printList(l2);
return 0;
}
```
代码中我们首先定义了链表节点的结构体`ListNode`,以及创建链表和打印链表的函数。在主函数中,我们首先让用户输入两个有序链表,然后输出这两个链表的内容。注意输入链表时输入-1表示链表的结束。