链表的相应操作
来源:互联网 发布:mac os 重装系统 编辑:程序博客网 时间:2024/05/21 12:42
一,目的
本节内容主要包括链表的排序,以及两个单链表的合并。
二,分析。
在对链表排序的时候,可以采用选择排序等方法,对比原来的对数进行排序,此时的不同便是如今要对结点进行排序。
而合并两个单链表,前提是两个单链表是有序的,这样合并完的单链表便也是有序的。
三,代码实现
struct Node{ int _data; Node* _next; Node(const int& x) :_data(x), _next(NULL) { }};
Node* Selete_Sort(Node* head) //选择排序{ if (head == NULL || head->_next == NULL) return head; Node* x, *y; for (x = head; x!= NULL; x = x->_next) { Node* temp = x; for (y = x->_next; y != NULL; y = y->_next) { if (y->_data < temp->_data) swap(temp, y); } if (temp != x) swap(x->_data, temp->_data); } return head;}
Node* Bubble_Sort(Node* head) //冒泡排序,很巧妙的实现{ Node* cur = head; Node* tail = NULL; while (cur != tail) { while (cur->_next != tail) { if (cur->_data > cur->_next->_data) swap(cur->_data, cur->_next->_data); cur = cur->_next; } tail = cur; cur = head; } return head;}
template<class T>Node<T>* sortTwoList(Node<T>* a, Node<T>* b) //递归实现合并两个有序单链表{ if (a == NULL) return b; if (b == NULL) return a; typedef Node<T> node; node* temp; if (a->data < b->data) { temp = a; temp->_next = sortTwoList(a->_next, b); } else { temp = b; temp->_next = sortTwoList(a, b->_next); } return temp;}
template<class T>Node<T>* sortTwoList1(Node<T>* a, Node<T>* b) //非递归实现{ if (a == NULL) return b; if (b == NULL) return a; Node<T>* x=a; Node<T>* y=b; Node<T>* cur = new Node<int>(-1); //创建一个头结点 Node<T>* temp = cur; while (x!= NULL || y!= NULL) { while(x && x->data <= y->data) { temp->_next = x; x = x->_next; temp = temp->_next; } if (x == NULL && y) //出来之后一定要先判空,而且要直接return,不然进入别的循环,会出现空指针的情况 { while (y) { temp->_next = y; y = y->_next; temp = temp->_next; } return cur->_next; } while (y&& y->data < x->data) { temp->_next = y; y = y->_next; temp = temp->_next; } if (y == NULL && x) { while (x) { temp->_next = x; x = x->_next; temp = temp->_next; } return cur->_next; }}
四,总结
好多代码面试时都要求手写代码的,然后我机写还是出了bug,还是太差,好好努力吧,把内容放到博客里,没事了可以看一下。
阅读全文
0 0
- 链表的相应操作
- flex tree的相应操作
- 数据预处理及相应的Rapidminer操作
- 建立员工表并完成相应操作
- 比较同结构的两个表的记录数目,并做相应操作!
- Python文件管理对相应目录下的进删除、重命名、移动文件等相应操作
- 循环读取某一列的值,进行相应的操作
- TortoiseSVN相应操作说明
- 使用函数传递参数来执行相应的数据库操作
- 怎样没有权限但能去操作相应的按钮
- fopen后面参数对文件操作的相应关系
- C# 直接访问sftp进行相应的操作
- MFC_BitmapTool(点击图标做相应的操作)
- ubuntu10.04中的输入法安装以及相应的一些操作
- 获取静态TableView选中的cell来执行相应操作
- Java Map 及相应的一些操作总结
- 在一个范围点击空白,则做出相应的操作
- (p169)构建二叉搜索树和进行相应的操作
- 一点一点学线程(四)concurrent包
- xshell连接树莓派lxpanel配置
- Codeforces Round #438 题解
- 数据结构——顺序表有序顺序表归并
- 搜集糖果
- 链表的相应操作
- OS之并发与并行,异步和多线程的区别
- Qt 学习之路 2(70):进程间通信
- 素数距离问题(水题一个)
- zabbix中文配置指南
- 汇编指令速查
- 跳槽 社保 买房
- 通过Bing Search APIs采集图片(python版)
- 测试职场之面试感悟