leetcode25. K 个一组翻转链表
生活随笔
收集整理的這篇文章主要介紹了
leetcode25. K 个一组翻转链表
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
給你一個(gè)鏈表,每?k?個(gè)節(jié)點(diǎn)一組進(jìn)行翻轉(zhuǎn),請(qǐng)你返回翻轉(zhuǎn)后的鏈表。
k?是一個(gè)正整數(shù),它的值小于或等于鏈表的長度。
如果節(jié)點(diǎn)總數(shù)不是?k?的整數(shù)倍,那么請(qǐng)將最后剩余的節(jié)點(diǎn)保持原有順序。
示例 :
給定這個(gè)鏈表:1->2->3->4->5
當(dāng)?k?= 2 時(shí),應(yīng)當(dāng)返回: 2->1->4->3->5
當(dāng)?k?= 3 時(shí),應(yīng)當(dāng)返回: 3->2->1->4->5
說明 :
你的算法只能使用常數(shù)的額外空間。
你不能只是單純的改變節(jié)點(diǎn)內(nèi)部的值,而是需要實(shí)際的進(jìn)行節(jié)點(diǎn)交換。
思路:找k鏈表的兩頭,反轉(zhuǎn)中間,并且操作連接部分的各種指針。代碼有詳細(xì)注釋
?
/*** Definition for singly-linked list.* public class ListNode {* int val;* ListNode next;* ListNode(int x) { val = x; }* }*/ class Solution {public ListNode reverseKGroup(ListNode head, int k) {ListNode dummy = new ListNode(0);dummy.next = head;ListNode pre = dummy;ListNode end = dummy;while (end.next != null) {//1、找k個(gè)for (int i = 0; i < k && end != null; i++) end = end.next;//2、不足k個(gè)按原順序,不用改變if (end == null) break;//3、記錄反轉(zhuǎn)鏈表的起點(diǎn)ListNode start = pre.next;//4、記錄反轉(zhuǎn)鏈表結(jié)尾的下一個(gè)節(jié)點(diǎn)ListNode next = end.next;//5、把反轉(zhuǎn)鏈表的next賦值為null,方便調(diào)用reverse()end.next = null;//6、前節(jié)點(diǎn)的下一個(gè)節(jié)點(diǎn)是反轉(zhuǎn)后的新頭pre.next = reverse(start);//7、反轉(zhuǎn)后的鏈表尾(之前的翻轉(zhuǎn)起點(diǎn))的next賦值為之前第4步記錄的nextstart.next = next;//8、更新下一個(gè)要翻轉(zhuǎn)k鏈表的前一個(gè)節(jié)點(diǎn)(也就是本次反轉(zhuǎn)后的末尾)pre = start;//9、賦值end,為下一次循環(huán)的第一步做準(zhǔn)備end = pre;}return dummy.next;}//翻轉(zhuǎn)標(biāo)準(zhǔn)鏈表(最后節(jié)點(diǎn)的next是null),返回新鏈表的頭private ListNode reverse(ListNode head) {ListNode pre = null;//前節(jié)點(diǎn)ListNode curr = head;//操作的節(jié)點(diǎn)while (curr != null) {//記錄本次節(jié)點(diǎn)的下一個(gè)節(jié)點(diǎn)ListNode next = curr.next;//賦值本次節(jié)點(diǎn)的next為前節(jié)點(diǎn)curr.next = pre;//更新前節(jié)點(diǎn)和操作節(jié)點(diǎn)pre = curr;curr = next;}return pre;} }?
總結(jié)
以上是生活随笔為你收集整理的leetcode25. K 个一组翻转链表的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 买车公积金贷款怎么贷 买车怎么公积金贷款
- 下一篇: Pandas数据排序——【按索引排序so