数据结构——单链表的基本操作
来源:互联网 发布:nginx 远程无法访问 编辑:程序博客网 时间:2024/06/04 19:04
做题碰到了,就写一写,也方便自己复习。
#include<iostream>#include<cstdlib>using namespace std;struct Node{int data;Node *next;};class LinkedList{public:LinkedList();void insert(int position, int content);void deleteByPosition(int position);void print();private:Node *head; // 链表头指针int size; // 链表内元素个数};LinkedList::LinkedList(){head = (Node *)malloc(sizeof(Node));head = NULL;size = 0;}/*插入一个元素content到链表的第position个位置,注意position从0开始如原始链表是 1 2 3,insert(0, 5)之后变成 5 1 2 3如果插入的位置在链表末尾或者之后,则直接将元素插入到链表末尾如原始链表是 1 2 3,insert(50, 6)之后变成 1 2 3 6第50个位置在当前链表大小之后,所以直接插入到链表末尾,也就是第3个位置*/void LinkedList::insert(int position, int content){Node *tem,*p,*q = head;tem = (Node *)malloc(sizeof(Node));tem->data = content;if(position > size) position = size;if (position == 0){tem->next = head;head = tem;}else{int k = 0;while (k < position - 1){head = head->next;k++;}p = head->next;head->next = tem;tem->next = p;head = q;}size++;}/*删除链表的第position个元素如果链表没有第position个元素,则不删除任何元素*/void LinkedList::deleteByPosition(int position){if(position >= 0 && position < size){Node *p, *q = head;if (position == 0){head = head->next;free(q);}else{int k = 0;while (k < position - 1){head = head->next;k++;}p = head->next;head->next = p->next;free(p);head = q;}size--;}}/*将链表内容打印到屏幕,每个元素后面都跟着一个制表符,并且最后一个元素的制表符后面需要换行*/void LinkedList::print(){Node *p = head;while (head!=NULL){cout << head->data << "\t";head = head->next;}cout << endl;head = p;}int main(){LinkedList obj;obj.insert(0,1);obj.print();obj.insert(1,2);obj.print();obj.insert(2,3);obj.print();obj.insert(3,4);obj.print();obj.insert(4,5);obj.print();obj.insert(8,50);obj.print();obj.insert(0,6);obj.print();obj.insert(3,7);obj.print();obj.deleteByPosition(3);obj.print();obj.deleteByPosition(0);obj.print();return 0;}
运行结果:
0 0
- 数据结构——单链表的基本操作
- 数据结构——单链表的基本操作
- 数据结构——单链表的基本操作
- 数据结构——图的基本操作
- 数据结构——栈的基本操作
- 数据结构——栈的基本操作
- 数据结构——栈的基本操作
- 数据结构——队列的基本操作
- 数据结构——堆栈的基本操作
- 数据结构——字符串的基本操作
- 数据结构—基本树的操作小结
- 数据结构与算法——单链表的基本操作
- 数据结构—单链表的部分基本操作(C语言)
- 单链表的基本操作-数据结构
- 【数据结构】单链表的基本操作
- 【数据结构】单链表的基本操作
- 数据结构--单链表的基本操作
- 数据结构-单链表的基本操作
- Toxophily
- CountDownLatch详解
- 一个爸爸每月要赚多少钱,才能撑起一个家?
- hdu4548 欧拉筛法 离线处理线性优化
- android:inputType常用取值
- 数据结构——单链表的基本操作
- php curl_init函数用法
- BSOJ : 2637 【模拟试题】数独
- Swift2-0基础_Functions(函数)
- HDU1505 City Game dp+若干次单调栈
- mac 操作
- Android ImageView的scaleType属性与adjustViewBounds属性
- Swift2-0基础_Closures(闭包)
- ios7的奇葩点