[数据结构]链表操作

来源:互联网 发布: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) {}};



    每次输入一个val值对链表中该值的节点进行访问操作,链表按照访问量降序排列。

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
原创粉丝点击