[数据结构]链表操作
来源:互联网 发布:mac 任务管理器快捷键 编辑:程序博客网 时间:2024/05/16 11:35
一、单向链表
1. 排序(插入升序):
假设所给的链表为不带头节点的链表,由于不带头节点的链表很难操作,首先将其添加一个头节点headNode。具体操作如下
void sortLinkList(Node *&head) { // ascendNode *headNode = new Node();headNode->next = head;if (head != NULL) {Node *curr = head->next;head->next = NULL;while (curr != NULL) {Node *befo = headNode, *tmp = curr->next;while (befo->next!=NULL && befo->next->val<=curr->val) {befo = befo->next;}curr->next = befo->next; //befo之后即为要插入的位置befo->next = curr;curr = tmp;}head = headNode->next;free(headNode);}}
2. 逆序:
同排序,先加上个头节点方便操作。
void reverseLinkList(Node *&head) {Node *nextNode = head->next;head->next = NULL;while(nextNode != NULL) {Node *tmp = nextNode->next;nextNode->next = head;head = nextNode;nextNode = tmp;}}
二、双向链表插入交换操作(带有头节点的):
问题描述:假设一个节点的数据结构如下,其中val为节点的值,freq为该节点的访问量。
struct DNode {int val;int freq;DNode *pre;DNode *next;DNode(int x=0) : val(x), freq(0), pre(NULL), next(NULL) {}};
bool findDNode(DNode *&head, int elem) {DNode *curr = head->next;while(curr!=NULL && curr->val!=elem) {curr = curr->next;}if (curr == NULL) return false;curr->freq++;DNode *currPre = curr->pre;while(currPre!=head && currPre->freq<curr->freq) {curr->pre = currPre->pre; // new curr pre 更新当前结点的前驱curr->pre->next = curr; // update the new curr pre's next to curr 更新新的前驱的后继为当前结点currPre->next = curr->next; // update the old curr pre's next to curr's old next 更新旧的前驱节点的后继为当前结点的旧的后继if (currPre->next != NULL) {currPre->next->pre = currPre;}curr->next = currPre; // make the old curr pre to curr's new next 当前节点的后继更新为旧的前驱currPre->pre = curr; // update the new curr's next(the curr's old pre)'s pre to curr 新的后继的前驱为当前结点currPre = curr->pre; // update currPre }return true;}
运行结果如下:
5
1 2 3 4 5
please input the Node you want to visit:
5
(5, 1)->(1, 0)->(2, 0)->(3, 0)->(4, 0)
3
(5, 1)->(3, 1)->(1, 0)->(2, 0)->(4, 0)
1
(5, 1)->(3, 1)->(1, 1)->(2, 0)->(4, 0)
1
(1, 2)->(5, 1)->(3, 1)->(2, 0)->(4, 0)
2
(1, 2)->(5, 1)->(3, 1)->(2, 1)->(4, 0)
3
(1, 2)->(3, 2)->(5, 1)->(2, 1)->(4, 0)
3
(3, 3)->(1, 2)->(5, 1)->(2, 1)->(4, 0)
4
(3, 3)->(1, 2)->(5, 1)->(2, 1)->(4, 1)
4
(3, 3)->(1, 2)->(4, 2)->(5, 1)->(2, 1)
4
(3, 3)->(4, 3)->(1, 2)->(5, 1)->(2, 1)
4
(4, 4)->(3, 3)->(1, 2)->(5, 1)->(2, 1)
未完待补充(不复习东西都忘完了......)
0 0
- [数据结构]链表操作
- 数据结构-链表操作
- 数据结构链表基本操作
- 数据结构链表操作1
- 数据结构-----链表基本操作
- 数据结构链表的操作
- 数据结构之链表操作
- 数据结构之链表操作
- 数据结构之链表操作
- 数据结构,链表基本操作
- 数据结构之链表操作
- 数据结构链表基本操作
- 数据结构 链表的基本操作
- 线性链表 各种操作整理 数据结构
- 数据结构:链表的简单操作
- C++数据结构之链表操作
- 数据结构:多项式链表的操作
- 数据结构链表的一些操作!
- bfs题目集锦
- excel的导入导出
- Leetcode #50. Pow(x, n) 幂实现 解题报告
- Modern PHP读书笔记一
- 一个新奇的东西,调试布局利器
- [数据结构]链表操作
- 二维情形下的最接近点对问题
- 向量时钟Vector Clock in Riak
- 前端笔记 CSS 5
- Android学习笔记(41):File存储
- mysql_query返回false原因
- 最大流部分
- 剑指Offer--025-二叉树中和为某一值的路径
- SDWebImage介绍