Problem
Given a linked list, reverse the nodes of a linked list k at a time and return its modified list.
If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is.
You may not alter the values in the nodes, only nodes itself may be changed.
Only constant memory is allowed.
Given this linked list: 1->2->3->4->5
For k = 2, you should return: 2->1->4->3->5
For k = 3, you should return: 3->2->1->4->5
Solutionclass Solution { public ListNode reverseKGroup(ListNode head, int k) { if (head == null) return null; ListNode dummy = new ListNode(0); dummy.next = head; ListNode pre = dummy; int i = 1; while (head != null) { if (i%k != 0) { head = head.next; } else { pre = reverse(pre, head.next); head = pre.next; } i++; } return dummy.next; } private ListNode reverse(ListNode pre, ListNode after) { ListNode cur = pre.next, next = pre.next.next; while (next != after) { cur.next = next.next; next.next = pre.next; pre.next = next; next = cur.next; } return cur; } }
文章版權(quán)歸作者所有,未經(jīng)允許請(qǐng)勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。
轉(zhuǎn)載請(qǐng)注明本文地址:http://specialneedsforspecialkids.com/yun/65441.html
摘要:注意這里,只要走到第位 Swap Nodes in Pairs For example,Given 1->2->3->4, you should return the list as 2->1->4->3. Solution public class Solution { public ListNode swapPairs(ListNode head) { if...
摘要:三指針法復(fù)雜度時(shí)間空間思路基本的操作鏈表,見注釋。注意使用頭節(jié)點(diǎn)方便操作頭節(jié)點(diǎn)。翻轉(zhuǎn)后,開頭節(jié)點(diǎn)就成了最后一個(gè)節(jié)點(diǎn)。 Swap Nodes in Pairs Given a linked list, swap every two adjacent nodes and return its head. For example, Given 1->2->3->4, you should ...
摘要:鏈表題目的集合雙指針法找中點(diǎn),分割,合并,翻轉(zhuǎn),排序。主函數(shù)對(duì)于長度為或的鏈表,返回找到中點(diǎn)分割鏈表并翻轉(zhuǎn)后半段為與前半段合并。當(dāng)移動(dòng)到最后一個(gè)元素,正好移動(dòng)到整個(gè)鏈表的頭部。 Problem Given a singly linked list L: L0 → L1 → … → Ln-1 → Ln reorder it to: L0 → Ln → L1 → Ln-1 → L2 → L...
摘要: Problem Implement a function to check if a linked list is a palindrome. Example Given 1->2->1, return true. Key create new list nodes: ListNode pre = null; //null, 1-2-3-4 //1-null, 2-3-4 //2-1...
摘要:建立結(jié)點(diǎn),指向可能要對(duì)進(jìn)行操作。找到值為和的結(jié)點(diǎn)設(shè)為,的前結(jié)點(diǎn)若和其中之一為,則和其中之一也一定為,返回頭結(jié)點(diǎn)即可。正式建立,,以及對(duì)應(yīng)的結(jié)點(diǎn),,然后先分析和是相鄰結(jié)點(diǎn)的兩種情況是的前結(jié)點(diǎn),或是的前結(jié)點(diǎn)再分析非相鄰結(jié)點(diǎn)的一般情況。 Problem Given a linked list and two values v1 and v2. Swap the two nodes in th...
閱讀 1966·2023-04-25 16:19
閱讀 3091·2021-11-24 09:39
閱讀 829·2021-11-16 11:44
閱讀 1688·2019-08-29 12:52
閱讀 1138·2019-08-26 13:33
閱讀 1073·2019-08-26 10:26
閱讀 2200·2019-08-23 16:42
閱讀 2567·2019-08-23 14:37