数据结构复习——线性表的链式存储实现(单向链表)
来源:互联网 发布:服装行业数据分析 编辑:程序博客网 时间:2024/05/16 17:07
上一篇讲了顺序存储,现在是实现另一种形式:链式存储。
除了做了单向链表,还有双向链表,十字链表。
先贴上最基础的单向链表。实现增删遍历,其余的操作都是大同小异。
#include<bits/stdc++.h>using namespace std;typedef struct Node * Nodeptr;typedef struct Node{ int data; //数据 struct Node * next; //指针} NODE; //NODE等价于struct Node,Nodeptr等价于struct Node *Nodeptr createLinklist()//创建{ int n,value; //记录创建节点的个数和值 Nodeptr Head=(Nodeptr)malloc(sizeof(Nodeptr));//创建头指针 if(Head==NULL) //判断失败操作 { printf("分配内存失败!\n"); exit(-1); } Head->next=NULL; //分配成功后初始化值 Nodeptr p=Head; //指针p始终指向表尾 printf("输入创建节点的个数:"); scanf("%d",&n); for(int i=0; i<n; i++) { scanf("%d",&value); Nodeptr NewNode=(Nodeptr)malloc(sizeof(NODE)); if(NewNode==NULL) { printf("分配内存失败!\n"); exit(-1); } NewNode->data=value; //值放入 NewNode->next=NULL; //末尾为空,两步标配的初始化操作 p->next=NewNode; //指向新节点 p=NewNode; //仍然让p指向末尾 } return Head;}void traverseLinklist(Nodeptr Head)//遍历{ Nodeptr p=Head->next; while(p!=NULL) { printf("%d ",p->data); p=p->next; } printf("\n"); return ;}void insertElement(Nodeptr Head,int pos, int value)//插入{ //将值为value的元素插入到pos位置 int i=0; Nodeptr p=Head; while(p!=NULL&&i<pos-1)//将指针定位到第pos-1个节点,其中可能位置不存在 { p=p->next; i++; } if(p==NULL||i>pos-1) { printf("位置不存在!\n"); return ; } Nodeptr NewNode=(Nodeptr)malloc(sizeof(Node));//分配内存 if(NewNode==NULL) { printf("分配内存失败!\n"); exit(-1); } NewNode->data=value; //赋值 NewNode->next=NULL; //初始化 Nodeptr q=p->next; //指向下一个节点 p->next=NewNode; //插入该节点 NewNode->next=q; //插入该节点 return ;}void deleteElement(Nodeptr Head,int pos)//删除{ //删除同上 int i=0; Nodeptr p=Head; while(p!=NULL&&i<pos-1) { p=p->next; i++; } if(p->next==NULL||i>pos-1) { printf("位置不存在!\n"); return ; } Nodeptr q=p->next; p->next=p->next->next; free(q); q=NULL; return ;}int main(){ Nodeptr head=NULL; head=createLinklist(); traverseLinklist(head); insertElement(head,4,10); traverseLinklist(head); return 0;}
0 0
- 数据结构复习——线性表的链式存储实现(单向链表)
- 数据结构复习——线性表的链式存储实现(双向链表)
- 数据结构:线性表的链式存储(单向链表)--Java实现
- 大话数据结构四:线性表的链式存储结构(单向循环链表)
- 大话数据结构四:线性表的链式存储结构(单向循环链表)
- 数据结构——单向链表的链式存储及实现
- 数据结构----纯C语言实现线性表的单向链式存储结构
- 数据结构之线性表——链表的链式存储(链式描述)
- 【数据结构复习】线性表的链式存储--单链表
- 线性表的Java实现--链式存储(单向链表)
- 数据结构复习—线性表的链式表示
- 数据结构复习——线性表的顺序存储实现
- 数据结构_线性表_链式存储_单向循环链表的基本操作
- 数据结构——线性表的链式存储
- 数据结构之线性表——栈的链式存储
- 数据结构之线性表——队列的链式存储
- 数据结构——线性表(链式存储)
- 线性表的链式存储结构(复习)
- Hadoop集群环境搭建
- UITextField 与 键盘
- 常用正则表达式示例
- android studio 的 Error occurred during initialization of VM Could not reserve enough space fo 解决办法
- [LC 94 144 145]Binary Tree Traversal ( preorder, inorder,postorder)
- 数据结构复习——线性表的链式存储实现(单向链表)
- How to Submit an URB
- SQL语句汇总
- java-设计模式之桥模式
- Ubuntu apt-get命令
- iOS---防止UIButton重复点击的三种实现方式
- Redis - Windows下的安装
- 断点调试
- hadoop配置独立模式(Standalone Mode)