鏈表類型題目

文章目錄

  • 簡介
  • 鏈表的常用技巧
  • 兩數相加
    • 原理
    • 代碼
    • 代碼||
  • 兩兩交換鏈表中的節點
    • 代碼
    • 原理
  • 重排鏈表(重要)
    • 原理
    • 代碼
  • 合并 K 個升序鏈表
    • 代碼
    • 遞歸代碼
  • K 個一組翻轉鏈表
    • 原理
    • 代碼

簡介

大家好,這里是jiantaoyab,這篇文章給大家帶來的是鏈表相關的題目練習和解析,希望大家能相互討論進步


鏈表的常用技巧

  • 畫圖

畫圖能更加清晰,方便我們去理解

  • 引入虛擬的頭結點

創建新的頭結點指向原來的鏈表,方便處理邊界情況

  • 多定義一個變量

多定義一個next就不用考慮先鏈接誰的問題

  • 快慢雙指針
  1. 判斷鏈表中是否有環
  2. 找環的入口
  3. 找鏈表倒數第n個節點
  • 鏈表逆序用頭插

兩數相加

https://leetcode.cn/problems/add-two-numbers/

https://leetcode.cn/problems/lMSNwu/ 兩數相加||

原理

在這里插入圖片描述

代碼

class Solution {
public:ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {ListNode* new_head = new ListNode(0); //創建哨兵位頭結點ListNode* tail = new_head;int x = 0;//記錄進位ListNode* cur1 = l1, *cur2 = l2;while(cur1 || cur2 || x){if(cur1){x += cur1->val;cur1 = cur1->next;}if(cur2){x += cur2->val;cur2= cur2->next;}tail->next = new ListNode(x % 10);tail = tail->next;x /= 10;}tail =  new_head->next;delete new_head;return tail;}
};

代碼||

class Solution {
public:ListNode* ReserveList(ListNode* head) {ListNode * head= nullptr;ListNode * curr = head;while(curr) {ListNode* next = curr->next;curr->next = prev;prev = curr;curr = next;}return prev;}ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {ListNode* new_head = new ListNode(0); //創建哨兵位頭結點ListNode* tail = new_head;int x = 0;//記錄進位l1 = ReserveList(l1);l2 = ReserveList(l2);ListNode* cur1 = l1, *cur2 = l2;while(cur1 || cur2 || x){if(cur1){x += cur1->val;cur1 = cur1->next;}if(cur2){x += cur2->val;cur2= cur2->next;}tail->next = new ListNode(x % 10);tail = tail->next;x /= 10;}tail =  new_head->next;tail = ReserveList(tail);delete new_head;return tail;}
};

兩兩交換鏈表中的節點

https://leetcode.cn/problems/swap-nodes-in-pairs/

代碼

  • 遞歸的方式

class Solution {
public:ListNode* swapPairs(ListNode* head) {//終止條件是鏈表只有一個節點 / 鏈表中沒有節點if(head == nullptr || head->next == nullptr) return head;ListNode* nnext =  swapPairs(head->next->next);ListNode* newhead = head->next;newhead->next = head;head->next = nnext;return newhead;}
};
  • 迭代的方式

原理

在這里插入圖片描述

class Solution {
public:ListNode* swapPairs(ListNode* head) {// 0個和1個節點直接返回就好if(head == nullptr || head->next == nullptr)  return head;ListNode* newhead = new ListNode(0); //哨兵位頭結點newhead->next = head;ListNode* prev =newhead;ListNode* cur = prev->next;ListNode* next = cur->next;ListNode* nnext = next->next;while(cur != nullptr && next != nullptr){//交換節點prev->next = next;next ->next = cur;cur ->next = nnext;//更新位置prev = cur;cur = nnext;if(cur != nullptr)next = cur->next;if(next != nullptr)nnext = next->next;}cur = newhead->next;delete newhead;return cur;}
};

重排鏈表(重要)


https://leetcode.cn/problems/LGjMqU/

原理

在這里插入圖片描述

代碼

class Solution {
public:void reorderList(ListNode* head) {// <=2節點的直接返回if(head == nullptr || head->next == nullptr || head->next->next ==nullptr) return ;//1.找到鏈表的中間節點ListNode * slow = head, *fast = head;while(fast && fast->next){slow = slow->next;fast = fast->next->next;}//2.將后半部分鏈表逆置ListNode* new_head = new ListNode(0);ListNode* cur = slow->next;     slow->next = nullptr; //斷開鏈表while(cur){ListNode* next = cur->next;cur->next = new_head->next;new_head->next = cur;cur = next;}//3.合并2個鏈表ListNode* ret_head = new ListNode(0);ListNode* prev = ret_head;ListNode* cur1 =head, *cur2 = new_head->next;while(cur1){//先放第一個鏈表prev->next = cur1;cur1 = cur1->next;prev = prev->next;//再放第二個鏈表if(cur2){prev->next = cur2;cur2 = cur2->next;prev = prev->next;}}delete new_head;delete ret_head;}
};

合并 K 個升序鏈表

https://leetcode.cn/problems/vvXgSW/

代碼

class Solution {struct cmp {bool operator() (const ListNode* l1, const ListNode* l2) {return l1->val > l2->val;}};public:ListNode* mergeKLists(vector<ListNode*>& lists) {//創建小根堆priority_queue<ListNode* ,vector<ListNode*>,cmp> heap;//讓所有鏈表的頭結點加入到小根堆中for(auto l :lists){if(l) heap.push(l);}//合并k個有序鏈表ListNode* new_head = new ListNode(0);ListNode* prev = new_head;//小根堆中還有元素說明還有鏈表沒到nullptrwhile(!heap.empty()){ListNode* min = heap.top();heap.pop();prev->next = min;prev = min;if(min->next) heap.push(min->next);}prev->next = nullptr;prev = new_head->next;delete new_head;return prev;}
};//自己用vs調試的時候,可以加上下面代碼調試一步一步看
int main()
{vector<ListNode*> lists = { new ListNode(1, new ListNode(4, new ListNode(5))),new ListNode(1, new ListNode(3, new ListNode(4))),new ListNode(2, new ListNode(6)) };mergeKLists(lists);
}

遞歸代碼

class Solution {
public:ListNode* MergeTowList(ListNode* l ,ListNode* r){if(l == nullptr) return r;if(r == nullptr) return l;ListNode new_head ;new_head.next = nullptr;ListNode* cur1 = l, *cur2 = r, *prev = &new_head ;while(cur1 && cur2){if(cur1->val >= cur2->val){prev = prev->next = cur2;cur2 = cur2->next;}else{prev = prev->next = cur1;cur1 = cur1->next;}}if(cur1) prev->next =cur1;if(cur2) prev->next =cur2;return new_head.next;}ListNode* Merge(vector<ListNode*>& lists, int left, int right) {if(left > right) return nullptr;if(left == right) return lists[left];int mid = (left + right) >> 1;ListNode* l = Merge(lists, left, mid); ListNode* r = Merge(lists, mid + 1, right); //合并2個有序鏈表return MergeTowList(l,r);}
public:ListNode* mergeKLists(vector<ListNode*>& lists) {      return Merge(lists, 0, lists.size() - 1);}
};

K 個一組翻轉鏈表

原理

在這里插入圖片描述

代碼

class Solution {
public:ListNode* reverseKGroup(ListNode* head, int k) {int N = 0;ListNode * p = head;while(p){p = p->next;N++;}N /= k; //劃分N組ListNode* new_head =  new ListNode(0);ListNode* prev = new_head;ListNode* cur = head;for(int i = 0; i < N; i++){ListNode *first = cur;for(int j = 0; j < k; j++){            ListNode* next = cur->next;cur->next = prev->next;prev->next = cur;cur = next;}prev = first;}//把不需要翻轉的接上prev->next = cur;cur = new_head->next;delete new_head;return cur;}
};

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/716336.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/716336.shtml
英文地址,請注明出處:http://en.pswp.cn/news/716336.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

[線代]自用大綱

部分內容整理自張宇和網絡 序 題型分布&#xff1a; 題型單題分值題目數量總分值選擇題5315填空題515解答題12112 *一道大題可能用到六部分所有知識 矩陣 性質 k k k倍和乘積行列式 ∣ k A ∣ k n ∣ A ∣ |kA|k^n|A| ∣kA∣kn∣A∣ ∣ A B ∣ ≠ ∣ A ∣ ∣ B ∣ |AB|≠…

DDE圖像增強

DDE&#xff08;Detail and Darkness Enhancement&#xff0c;細節和暗部增強&#xff09;是一種用于增強圖像細節和暗部區域的方法。其原理可以簡要概括如下&#xff1a; 細節增強&#xff1a;在圖像中突出顯示細節信息&#xff0c;使得圖像更加清晰和具有視覺沖擊力。這可以通…

藍橋杯刷題--python-15-二分(進階)

503. 借教室 - AcWing題庫 n,mmap(int,input().split()) class_list(map(int,input().split())) class_[0]class_ d[0] s[0] t[0] for _ in range(m): dj,sj,tjmap(int,input().split()) d.append(dj) s.append(sj) t.append(tj) def check(k): b[0]*(n2) …

如何解決微服務的數據一致性分發問題?

介紹 系統架構微服務化以后,根據微服務獨立數據源的思想,每個微服務一般具有各自獨立的數據源,但是不同微服務之間難免需要通過數據分發來共享一些數據,這個就是微服務的數據分發問題。Netflix/Airbnb等一線互聯網公司的實踐[參考附錄1/2/3]表明,數據一致性分發能力,是構…

在嵌入式設備中用多項式快速計算三角函數和方根

慣性傳感器的傾角計算要用到三角函數. 在 MCS-51, Cortex M0, M3 之類的芯片上編程時, 能使用的資源是非常有限, 通常只有兩位數KB的Flash, 個位數KB的RAM. 如果要使用三角函數和開方就要引入 math.h, 會消耗掉10KB以上的Flash空間. 在很多情況下受硬件資源限制無法使用 math.…

【 10X summary report】怎么看?詳細解讀筆記

報告內容 在開始正式的分析之前&#xff0c;需要查看在對齊和計數過程中生成的任何總結統計信息。下圖是由Cell Ranger工具創建的10X總結報告&#xff0c;在從10X scRNA-seq實驗生成計數矩陣時會生成。 The left half of the report describes sequencing and mapping statist…

賣wordpress網站模板的網站

WP模板牛 http://www.wpniu.com 上面有很多免費wordpress模板資源的網站&#xff0c;除了免費模板&#xff0c;還有付費模板。 My模板(我的模板) http://www.mymoban.com 老牌網站模板資源站&#xff0c;上面有wordpress模板、帝國CMS模板、WooCommerce模板可以直接免費下載…

Linux whois命令教程:查詢域名所有者信息(附案例詳解和注意事項)

Linux whois命令介紹 whois命令是一個用于查詢域名所有者信息的工具。它可以直接從命令行進行查詢&#xff0c;這對于沒有圖形用戶界面的系統或者需要在shell腳本中進行查詢的情況非常有用。 Linux whois命令適用的Linux版本 whois命令在大多數Linux發行版中都可以使用&…

C++之stack

1、stack簡介 stack是實現的一個先進后出&#xff0c;后進先出的容器。它只有一個出口&#xff0c;只能操作最頂端元素。 2、stack庫函數 &#xff08;1&#xff09;push() //向棧壓入一個元素 &#xff08;2&#xff09;pop() //移除棧頂元素 &#xff08;3…

基于springboot+vue的中國陜西民俗網

博主主頁&#xff1a;貓頭鷹源碼 博主簡介&#xff1a;Java領域優質創作者、CSDN博客專家、阿里云專家博主、公司架構師、全網粉絲5萬、專注Java技術領域和畢業設計項目實戰&#xff0c;歡迎高校老師\講師\同行交流合作 ?主要內容&#xff1a;畢業設計(Javaweb項目|小程序|Pyt…

在 Angular 中使用 Renderer2

Renderer2 類 Renderer2 類是 Angular 提供的一個抽象服務&#xff0c;允許在不直接操作 DOM 的情況下操縱應用程序的元素。這是推薦的方法&#xff0c;因為它使得更容易開發可以在沒有 DOM 訪問權限的環境中渲染的應用程序&#xff0c;比如在服務器上、在 Web Worker 中或在原…

Java如何剪切視頻

背景&#xff1a;如何使用Java批量切割視頻 FFmpeg 是一個強大的開源多媒體處理工具&#xff0c;被廣泛應用于音視頻的錄制、轉碼、編輯等方面。它支持幾乎所有主流的音視頻格式&#xff0c;能夠在各種操作系統平臺上運行&#xff0c;包括 Windows、macOS 和 Linux。FFmpeg 提…

nginx,php-fpm

一&#xff0c;Nginx是異步非阻塞多進程&#xff0c;io多路復用 1、master進程&#xff1a;管理進程 master進程主要用來管理worker進程&#xff0c;具體包括如下4個主要功能&#xff1a; &#xff08;1&#xff09;接收來自外界的信號。 &#xff08;2&#xff09;向各worker進…

SAP PP學習筆記04 - BOM2 -通過Serial來做簡單的BOM變式配置,副明細,BOM狀態,BOM明細狀態,項目種類,遞歸BOM

本章繼續講BOM。 本章講通過Serial來做簡單的BOM變式配置。還講了BOM的相關概念&#xff1a;副明細&#xff0c;BOM狀態&#xff0c;BOM明細狀態&#xff0c;項目種類&#xff0c;遞歸BOM 等。 1&#xff0c;通過Serial&#xff08;序列號&#xff09;來做簡單的 VC&#xff0…

spring自定義注解之-ElementType.METHOD方法級注解聲明

自定義注解類型和常用場景 可以參考之前的文章 &#xff1a; ElementType.FIELD字段級注解聲明 如果在項目中&#xff0c;多處地方都需調用到同一個方法進行邏輯處理&#xff0c;且與方法的業務邏輯無關&#xff0c;比如監控&#xff0c;日志等&#xff0c;則可用自定義的方法…

【JavaSE】面向對象——繼承性

繼承性 繼承性的概念 所謂繼承&#xff0c;就是程序猿在保持原有類特性的基礎上進行擴展&#xff0c;增加新功能&#xff0c;這樣的類被稱為派生類或者子類&#xff0c;原有類被稱為超類或者基類。 在對于繼承性概念進行書寫前&#xff0c;我曾查閱許多資料來保證對其表達的…

Some collections -- 2024.3

一、TensorFlow Android (dataset: Mnist) We used TensorFlow to define and train our machine learning model, which can recognize handwritten numbers, called a number classifier model in machine learning terminology. We transform the trained TensorFlow mod…

C++學習第五天(內存管理)

1、內存分布 int globalVar 1; static int staticGlobalVar 1; void Test() {static int staticVar 1;int localVar 1;int num1[10] { 1, 2, 3, 4 };char char2[] "abcd";const char* pChar3 "abcd";int* ptr1 (int*)malloc(sizeof(int) * 4);int…

2024.03.01作業

1. 基于UDP的TFTP文件傳輸 #include "test.h"#define SER_IP "192.168.1.104" #define SER_PORT 69 #define IP "192.168.191.128" #define PORT 9999enum mode {TFTP_READ 1,TFTP_WRITE 2,TFTP_DATA 3,TFTP_ACK 4,TFTP_ERR 5 };void get_…

高維中介數據:基于交替方向乘子法(ADMM)的高維度單模態中介模型的參數估計(入門+實操)

全文摘要 用于高維度單模態中介模型的參數估計&#xff0c;采用交替方向乘子法&#xff08;ADMM&#xff09;進行計算。該包提供了確切獨立篩選&#xff08;SIS&#xff09;功能來提高中介效應的敏感性和特異性&#xff0c;并支持Lasso、彈性網絡、路徑Lasso和網絡約束懲罰等不…