#include <iostream>
using namespace std;
struct ListNode {
int val; //存储数据
ListNode *next; //next指针
ListNode(int x) : val(x), next(NULL) {}
};
ListNode* creatLinkedList(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 printLinkedList(ListNode* head)
{
ListNode* curNode = head;
while(curNode != NULL)
{
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 = creatLinkedList(arr,n);
printLinkedList(head);
return 0;
}
C++ 链表的建立与使用
最新推荐文章于 2024-05-16 21:12:43 发布