这么做国外网站的国内镜像站,现在开天猫店需要多少钱,网站开发自适应,罗湖做网站报价链表创建 链表打印全部内容 获取链表长度 链表根据指定位置添加元素 链表根据指定位置删除元素
#include iostream
using namespace std;// 1、创建结构体// typedef 经常在结构中使用 typedef 别名
typedef struct node {int date;struct node* next; // 必须要自己…链表创建 链表打印全部内容 获取链表长度 链表根据指定位置添加元素 链表根据指定位置删除元素
#include iostream
using namespace std;// 1、创建结构体// typedef 经常在结构中使用 typedef 别名
typedef struct node {int date;struct node* next; // 必须要自己用自己,否则会陷入循环中
}Node; // 结构类型别名// 2、创建链表 创建长度为n的链表Node* Nodeinit(int n) {// 创建 头节点Node* head new Node;head-date 0;head-next NULL;// 创建 暂存节点Node* per head;for (int i 0; i n; i) {Node* p new Node; // 创建 一个节点p-next NULL; // 指向下一个点, 先设空p-date 0; // 赋值 0per-next p; // 将 暂存节点 链接起来 这样暂存节点的下一个就是新的暂存节点进行循环per p; // 将里面的值也赋过去}return head;}// 3、查看链表所有数据
void NodeDisplay(Node *tou) {Node* p tou-next;while (p ! NULL) {std::cout p-date - ;p p-next;}std::cout NULL std::endl;
}// 4、获取链表长度
int Nodelen(Node *node) {Node* p node-next;int i 0;while (p ! NULL) {p p-next;i;}std::cout 链表长度 i std::endl;return i;}// 指定位置插入替换链表数据 (头节点、插入位置、插入数据)
void NodeInsert(Node* head, int index, int date) {int n Nodelen(head); // 链表长度// 超出范围则报错if (index 0 || index n) {throw index error; //如果插入位置超出链表长度抛出异常//std::cout 插入位置有误: index std::endl;}//临时存放节点Node* per head;for (int i 0; i index; i){// 循环next到index位置per per-next;}Node* Node1 new Node;// 新节点 输入数据Node1-date date;// 新节点指向 要使用 原节点的指向Node1-next per-next;// 原节点指向新节点 per-next Node1;std::cout 插入成功: index std::endl;
}// 指定位置删除链表中的元素void delNode(Node* head, int index) {int n Nodelen(head); // 链表长度// 超出范围则报错if (index 0 || index n) {throw index error; //如果插入位置超出链表长度抛出异常//std::cout 插入位置有误: index std::endl;}//临时存放节点Node* per head;for (int i 0; i index; i) {per-next;}// 将要删除的节点拿出来Node* p per-next;// 接入下下个节点per-next per-next-next;std::cout 删除成功, 位置: index std::endl;// 删除拿出来的节点delete p;
}
// 查链表是否存在某元素// 删除链表指定元素// 演示
int main(int argc, char** argv) {// 初始化 链表Node* MainHead Nodeinit(5);// 打印链表NodeDisplay(MainHead);// 获取链表长度Nodelen(MainHead);// 插入替换某节点链表首地址, 链表位置, 插入内容NodeInsert(MainHead, 3, 1);// 打印链表NodeDisplay(MainHead);// 删除指定位置的链表元素delNode(MainHead, 4);// 打印链表NodeDisplay(MainHead);return 0;
}