#include <iostream>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
//使用数组创建链表
ListNode* createLinkedList(int arr[], int n){
if(n == 0){
return NULL;
}
ListNode* head = new ListNode(arr[0]);
ListNode* curNode = head;
for(int i = 1; i < n; ++i){
curNode->next = new ListNode(arr[i]);
curNode = curNode->next;
}
return head;
}
//打印链表
void printListNode(ListNode* head){
ListNode* curNode = head;
while(curNode){
cout << curNode->val << " -> ";
curNode = curNode->next;
}
cout << "NULL" << endl;
return;
}
int main()
{
int arr[] = {1, 2, 3, 4, 5};
int n = sizeof(arr) / sizeof(int);
ListNode* head = createLinkedList(arr, n);
printListNode(head);
return 0;
}
链表的c++实现
最新推荐文章于 2024-09-25 15:54:35 发布