单链表基本操作
2016-01-20 21:29
288 查看
主要是单链表的一些常见操作:像创建链表,删除结点,插入结点,链表逆序,按大小排序等
测试结果:
#include <iostream> using namespace std; struct Node { int val; Node *next; Node(int x) :val(x), next(nullptr){} }; //创建带有头结点的单链表 void Create(Node *head) { int n; Node *p(head), *q; cout << "请输入元素个数及相应数据:"; cin >> n; while (n--) { int value; cin >> value; q = new Node(value); q->next = nullptr; p->next = q; p = q; } } //获得链表长度 int GetSize(Node *head) { int num = 0; Node *p = head->next; while (p) { num++; p = p->next; } return num; } //输出链表元素 void Print(Node *head) { Node *p = head->next; while (p) { cout << p->val << ' '; p = p->next; } } //删除值为x的结点 void Delete(Node *head, int x) { Node *p(head), *q; while (p->next && p->next->val != x) { p = p->next; } if (p->next) { q = p->next; p->next = q->next; delete[] q; } else { cout << "链表不存在值为" << x << "的结点" << endl; } } //链表逆序 void Reverse(Node *head) { Node *p(head->next), *q(head->next); head->next = nullptr; while (p) { q = q->next; p->next = head->next; head->next = p; p = q; } } //在升序链表中插入结点使之仍然有序 void Insert(Node *head, Node *t) { Node *p(head); while (p->next && p->next->val < t->val) { p = p->next; } t->next = p->next; p->next = t; } //按升序排列 void Sort(Node *head) { Node *p, *q; p = head->next; head->next = nullptr; while (p) { q = p; p = p->next; q->next = nullptr; Insert(head, q); } } void Tips() { cout << "\n请按键选择相应操作" << endl; cout << "-------------------------" << endl; cout << "1.输出链表" << endl; cout << "2.删除链表某一结点" << endl; cout << "3.链表逆序" << endl; cout << "4.按升序排列" << endl; cout << "-------------------------" << endl; } int main() { Node *head = new Node(0); head->next = nullptr; Create(head); Tips(); char c; while (cin >> c) { switch (c) { case '1': Print(head); break; case'2': int valToDelete; cout << "请输入要删除结点的值:"; cin >> valToDelete; Delete(head, valToDelete); Print(head); break; case'3': Reverse(head); Print(head); break; case '4': Sort(head); Print(head); break; default: break; } Tips(); } }
测试结果:
相关文章推荐
- ASP.NET 日志
- 机器学习公开课笔记(8):k-means聚类和PCA降维
- mysql数据迁移到mongodb之工具迁移
- 网站攻防
- SQLite
- 如何让软件绑定计算机硬件
- 关于Oracle数据库的用户权限问题补充
- linux字符设备驱动程序(一)----------分配设备号并注册设备
- KMP 模式串匹配算法
- hdu 2035
- LeetCode 225 Implement Stack using Queues(用队列来实现栈)(*)
- 快速安装配置Zabbix
- rpm -qa | grep jdk
- C++开发人脸性别识别教程(14)——灰度图像识别BUG处理
- caffe-windows配置 cuda6.5+vs2012
- 二元组建图
- 媒体查询
- 注册码原理
- R文件无法自动生成之处理办法汇总
- web.xml中/与/*的区别