1、顺序表(数组):
C++中只要定义了一个数组,就分配一段连续存储空间。
元素的逻辑顺序域物理顺序一致,第i个元素在第i个位。
可顺序访问a[0],a[1],.....,也可随机访问a[i]
int a[n] = {1,2,3}; //静态分配存储空间,预先分配4*n B
// n难以确定,若用到的空间远小于n,造成空间浪费
//若进行插入操作,超出预分配的空间,导致溢出
int *p =new int[n]; //动态分配,根据需求随时创建,但耗时
Note:记得用完释放 delete[] p;
数组逻辑顺序与物理顺序相同,进行插入和删除操作,一般平均移动半个数组的元素,相当耗时 
2、引入链表
链接方式存储,适用于插入或删除频繁,存储空间需求不定的情况

#include<iostream>
using namespace std;
#include<vector>
//链表结点结构
class ListNode
{
public:
int data; //数据域
ListNode* next; //指针域
ListNode(int val) //有参构造,data赋值
{
data = val;
}
};
vector<int> inputV()
{
int n;
cout << "请输入待排序组元素的个数" << endl;
cin >> n;
vector<int> nums;
cout << "请输入待排序组"<< endl;
for (int i = 0; i < n; i++)
{
int temp;
cin >> temp;
nums.push_back(temp);
}
return nums;
}
//创建链表
ListNode* creat(vector<int>& nums)
{
//创建头节点
ListNode* head = NULL;
head = new ListNode(0); //头结点数据域可为空
ListNode* p = head; //记录头指针
for (vector<int>::iterator it = nums.begin(); it != nums.end(); it++)
{
ListNode* pNewNode = new ListNode(*it);//创建新结点
p->next = pNewNode; //上个节点指针域放新节点的地址
p = pNewNode;//更新结点
}
return head;
}
void printList(ListNode* L) //传入头指针,利用头指针可找到整个链表
{
while (L->next != NULL)
{
L = L->next; //头结点数据不用
cout << L->data << " ";
}
cout << endl;
}
int main()
{
vector<int> nums;
nums = inputV(); //inputNum()用户输入一组数字,保存在vector中
ListNode* head = NULL;
head = creat(nums);
printList(head);
system("pause");
return 0;
}
本文探讨了C++中数组与链表在内存分配、访问方式及操作效率上的差异,特别强调了链表在频繁插入删除场景中的优势。通过实例展示了如何使用vector和链表实现动态存储,并介绍了创建链表的方法和打印链表的函数。
803

被折叠的 条评论
为什么被折叠?



