日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > java >内容正文

java

【LeetCode笔记】25. K个一组翻转链表(Java、链表、递归)

發布時間:2024/7/23 java 40 豆豆
生活随笔 收集整理的這篇文章主要介紹了 【LeetCode笔记】25. K个一组翻转链表(Java、链表、递归) 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

文章目錄

  • 題目描述
  • 思路 & 代碼
      • 更新 - 精簡版
      • 三刷 - 再更新版

題目描述

  • 審題很重要。。一開始以為是一組換兩個,但是實際上是一組全部都要互換。
  • 字節超高頻題!要認真點記錄

思路 & 代碼

  • 用回溯來做,可以分解成:每次都用head和之后的k-1個結點進行翻轉操作,在翻轉之前先把第k+1個結點傳入下一個翻轉函數,然后再翻轉當前Head,并且連接上第k+1個結點。
  • 題目不難,但是要注意考慮邊界條件,還有由于鏈表性質導致的問題(指針丟失、弄混等)。
/*** Definition for singly-linked list.* public class ListNode {* int val;* ListNode next;* ListNode() {}* ListNode(int val) { this.val = val; }* ListNode(int val, ListNode next) { this.val = val; this.next = next; }* }*/ class Solution {// 回溯public ListNode reverseKGroup(ListNode head, int k) {if(k == 1){return head;}// 思路:先翻轉一組,然后遞歸翻轉下一組ListNode end = head;// end為當前組最后一個結點// 時間復雜度O(n),必做for(int i=0;i<k-1;i++){end = end.next;// 說明并不存在最后一個結點,結束if(end == null){return head;}}// 存在最后一個結點,繼續做// 下一個k組鏈表的起點// 結尾記得把這玩意連上end = end.next;if(end != null){end = reverseKGroup(end, k);}// 開始翻轉當前K組ListNode first = head;ListNode nowNode = head.next;ListNode temp;// 時間復雜度O(n)for(int i=0;i < k-1;i++){temp = nowNode.next;nowNode.next = first;first = nowNode;// 最后一步無需更新nowNodeif(i != k-2){ nowNode = temp;}}// 當前k尾與下一組K頭銜接head.next = end;return nowNode;} }

更新 - 精簡版

/*** Definition for singly-linked list.* public class ListNode {* int val;* ListNode next;* ListNode() {}* ListNode(int val) { this.val = val; }* ListNode(int val, ListNode next) { this.val = val; this.next = next; }* }*/ class Solution {// 遞歸public ListNode reverseKGroup(ListNode head, int k) {ListNode lastNode = head;for(int i = 0; i < k - 1; i++) {lastNode = lastNode.next;// 不夠 k 個的情況if(lastNode == null) {return head;}}// 1. 先繼續往后走ListNode nextHead = null;if(lastNode.next != null) {nextHead = reverseKGroup(lastNode.next, k);}// 2. 翻轉當前kListNode now = head, pre = null;for(int i = 0; i < k; i++) {ListNode temp = now.next;now.next = pre;pre = now;now = temp;}// 3. 銜接head.next = nextHead;return pre;} }

三刷 - 再更新版

  • 有一說一,感覺這個更新 nice 多了!
class Solution {public ListNode reverseKGroup(ListNode head, int k) {if(head == null) return head;ListNode nowLast = head;for(int i = 0; i < k - 1; i++) {if(nowLast.next == null) return head; // 湊不夠,直接returnnowLast = nowLast.next;}ListNode now = head, pre = reverseKGroup(nowLast.next, k);while(pre != nowLast) {ListNode temp = now.next;now.next = pre;pre = now;now = temp;}return nowLast;} }

總結

以上是生活随笔為你收集整理的【LeetCode笔记】25. K个一组翻转链表(Java、链表、递归)的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。