将int a[MAX_SIZE] = {1, 2, 3, 4, 2, 3, 5, 6, 7, 8, 9, 10};的每个元素插入链表
时间: 2023-10-24 14:10:12 浏览: 90
好的,我理解了你的问题。以下是将数组a的每个元素插入链表的代码:
```c++
#include <iostream>
using namespace std;
const int MAX_SIZE = 12;
struct ListNode {
int val;
ListNode* next;
ListNode(int x) : val(x), next(NULL) {}
};
ListNode* insert(ListNode* head, int val) {
ListNode* node = new ListNode(val);
if (!head) {
head = node;
} else {
ListNode* cur = head;
while (cur->next) {
cur = cur->next;
}
cur->next = node;
}
return head;
}
int main() {
int a[MAX_SIZE] = {1, 2, 3, 4, 2, 3, 5, 6, 7, 8, 9, 10};
ListNode* head = NULL;
for (int i = 0; i < MAX_SIZE; i++) {
head = insert(head, a[i]);
}
ListNode* cur = head;
while (cur) {
cout << cur->val << " ";
cur = cur->next;
}
cout << endl;
return 0;
}
```
阅读全文