链表
#include<iostream>
using namespace std;
struct ListNode {
int val;
ListNode* next;
ListNode(int value) : val(value), next(nullptr) {}
};
ListNode* createSList(int* nums, int sz) {
ListNode* head = nullptr;
ListNode* tail = nullptr;
for (int i = 0; i < sz; ++i) {
ListNode* newNode = new ListNode(nums[i]);
if (tail == nullptr) {
head = tail = newNode;
} else {
tail->next = newNode;
tail = newNode;
}
}
return head;
}
void destroySList(ListNode* head) {
while (head != nullptr) {
ListNode* temp = head;
head = head->next;
delete temp;
}
}
int main() {
int arr[] = {1, 2, 3, 4, 5, 6};
int sz = sizeof(arr) / sizeof(arr[0]);
ListNode* head = createSList(arr, sz);
ListNode* p = head;
//遍历链表
while(p != nullptr){
cout << p -> val << " ";
p = p -> next;
}
// 在程序结束前释放链表占用的内存
destroySList(head);
return 0;
}
1 2 3 4 5 6