链表划分为左小、中相等、右大
生活随笔
收集整理的這篇文章主要介紹了
链表划分为左小、中相等、右大
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
解題思路:將一個鏈表分成三個鏈表,最后重新連接三個鏈表
(1)分成三個鏈表的過程是一致的:以左小鏈表為例依次遍歷原鏈表的每一個節點cur,當cur->data<pivot時,把cur取出,
添加到左小鏈表末尾,直到遍歷完整個原鏈表為止。
(2)生成左小、中相等、右大鏈表后,怎么連接三個鏈表并返回頭結點是難點!(因為不知道三個鏈表是否為空)
#include<iostream>
using namespace std;typedef struct TNode
{int data;struct TNode* next;
}TNode;TNode* createL(int n) //創建鏈表
{TNode* head = NULL;TNode* tial = NULL;for (int i = 0; i < n; i++){TNode* node = new TNode;node->next = NULL;cout << "請輸入";cin >> node->data;if (head == NULL){head = node;tial = head;}else{tial->next = node;tial = node;}}tial->next = NULL;return head;
}void travel(TNode* head)
{cout << "輸出結果:" << endl;TNode* p = head;while (p != NULL){cout << p->data << endl;p = p->next;}
}TNode* listPartition(TNode* head, int pivot) //鏈表劃分
{TNode* sh = NULL;TNode* st = NULL;TNode* eh = NULL;TNode* et = NULL;TNode* bh = NULL;TNode* bt = NULL;//依次遍歷每一個元素TNode* cur = head;TNode* s = NULL; //輔助變量,用于保存cur節點的下一個節點,防止斷鏈while (cur != NULL){s = cur->next;cur->next = NULL;//將當前結點cur的指針域設為空,保證每個鏈表的新增節點為最后一個節點if (cur->data < pivot){if (sh == NULL){sh = cur;st = cur;}else{st->next = cur;st = cur;}}else if (cur->data == pivot){if (eh == NULL){eh = cur;et = cur;}else{et->next = cur;et = cur;}}else if (cur->data > pivot){if (bh == NULL){bh = cur;bt = cur;}else{bt->next = cur;bt = cur;}}cur = s;}//難點:將三個不知道是否為空鏈表的鏈表進行鏈接成一條鏈表,返回最終的頭結點
//依次從左到右假設每個鏈表不為空時,尾節點指針域的指向if (st != NULL){st->next = (eh != NULL) ? eh : bh;}if (et != NULL){et->next = bh;}return st != NULL ? sh : et != NULL ? eh : bh;
}
int main()
{TNode* head = NULL;head = createL(7);travel(head);head = listPartition(head, 3);travel(head);return 0;
}
總結
以上是生活随笔為你收集整理的链表划分为左小、中相等、右大的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 往有序单循环链表的插入元素使原链表依旧有
- 下一篇: 获取视频的每一帧,并保存为.jpg图片