8.链表 --最简单的链表
/*
最常用的数据结构是数组,其次是链表
数组的缺点是:插入和删除的时候内存开销大,因为元素需要移动
链表的插入速度非常快,元素不需要移动
1.数据域
2.链接域
*/
#include <windows.h> #include <iostream> #include <stdio.h> using namespace std; typedef struct listNode //节点对象 { //1.数据域 int data; //2.链接域 or 指针域 struct listNode *link; }node; node *create3()//创建3个节点的链表 { node *first, *second, *third; first = (node *)malloc(sizeof(node));//给第1个节点分配内存空间,并且指针转换 second = (node *)malloc(sizeof(node)); third = (node *)malloc(sizeof(node)); third->link = NULL;//最后1个元素的地址应该是null third->data = 30; second->link = third; second->data = 20; first->link = second; first->data = 10; return first; } int main() { node *list = create3(); cout << list->link->link->data << endl; while (NULL != list) { cout << list->data << endl; list = list->link; } delete list; list = NULL; system("pause"); return 0; }