【leetcode刷题笔记】Reverse Nodes in k-Group

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.

For example,
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



题解:思路很简单,一步步做就可以了。除了题目要求实现的函数,另外实现了两个函数:

private ListNode[] reverseSub(ListNode head,int k) 该函数将head所指向的长度为k的链表反转,返回一个大小为2的数组,数组中第一个元素是反转后的链表的头节点,第二个元素是反转后的链表的尾节点。

private int getlength(ListNode head) 该函数返回head所指向的链表的长度。

在reverseKGroup函数中,首先计算原链表的长度len,那么需要反转的组的数目就是len/k,接下来调用reverseSub函数len/k次,反转每一段链表,然后根据返回的首尾指针把它们串起来。最后根据len%k是否为0判断链表中是否有不需要反转的元素,如果有,把它们链在链表最后面返回。

代码如下:

 1 /**
 2  * Definition for singly-linked list.
 3  * public class ListNode {
 4  *     int val;
 5  *     ListNode next;
 6  *     ListNode(int x) {
 7  *         val = x;
 8  *         next = null;
 9  *     }
10  * }
11  */
12 public class Solution {
13     private ListNode[] reverseSub(ListNode head,int k){
14         ListNode[] answer = new ListNode[2];
15         answer[1] = head;
16         ListNode prev = null;
17         for(int i = 0;i < k;i++){
18             ListNode temp = head.next;
19             head.next = prev;
20             prev = head;
21             head = temp;
22         }
23         answer[0] = prev;
24         return answer;
25     }
26     private int getlength(ListNode head){
27         int count = 0;
28         while(head != null){
29             count ++;
30             head = head.next;
31         }
32         return count;
33     }
34
35     public ListNode reverseKGroup(ListNode head, int k) {
36         int len = getlength(head);
37         if(len < k)
38             return head;
39
40         ListNode answer = null;
41         ListNode tail = new ListNode(0);
42         int for_num = len / k;
43         for(int i = 0;i < for_num;i++){
44             ListNode h = head;
45
46             //find next starter
47             for(int j = 0;j < k;j++)
48                 head = head.next;
49
50             ListNode[] temp = reverseSub(h, k);
51             if(answer == null){
52                 answer = temp[0];
53                 tail = temp[1];
54             }
55             else {
56                 tail.next = temp[0];
57                 tail = temp[1];
58             }
59         }
60
61         if(len%k != 0)
62             tail.next = head;
63         else
64             tail.next = null;
65
66         return answer;
67     }
68 }

【leetcode刷题笔记】Reverse Nodes in k-Group

时间: 2024-10-02 07:21:49

【leetcode刷题笔记】Reverse Nodes in k-Group的相关文章

【leetcode刷题笔记】Merge k Sorted Lists

Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity. 题解:最开始用了最naive的方法,每次在k个链表头中找出最小的元素,插入到新链表中.结果果断TLE了. 分析一下,如果这样做,每取出一个节点,要遍历k个链表一次,假设k个链表一共有n个节点,那么就需要O(nk)的时间复杂度. 参考网上的代码,找到了用最小堆的方法.维护一个大小为k的最小堆,存放当前k

【leetcode刷题笔记】Reverse Linked List II

Reverse a linked list from position m to n. Do it in-place and in one-pass. For example:Given 1->2->3->4->5->NULL, m = 2 and n = 4, return 1->4->3->2->5->NULL. Note:Given m, n satisfy the following condition:1 ≤ m ≤ n ≤ lengt

【leetcode刷题笔记】Evaluate Reverse Polish Notation

Evaluate the value of an arithmetic expression in Reverse Polish Notation. Valid operators are +, -, *, /. Each operand may be an integer or another expression. Some examples: ["2", "1", "+", "3", "*"] -&g

【leetcode刷题笔记】Add Two Numbers

You are given two linked lists representing two non-negative numbers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list. Input: (2 -> 4 -> 3) + (5 -> 6 ->

【leetcode刷题笔记】Scramble String

Given a string s1, we may represent it as a binary tree by partitioning it to two non-empty substrings recursively. Below is one possible representation of s1 = "great": great / gr eat / \ / g r e at / a t To scramble the string, we may choose a

【leetcode刷题笔记】Max Points on a Line

Given n points on a 2D plane, find the maximum number of points that lie on the same straight line. 题解: 思路比较简单,每条直线都可以表示为y=kx+b,所以对于任意三点,如果它们共线,那么它们中任意两点的斜率都相等. 所以就遍历points数组,对其中的每一个元素计算它和位于它后面的数组元素的斜率并保存在一个hashmap中. 这个hashmap的键就是两点构成直线的斜率,值就是和当前元素po

【leetcode刷题笔记】Validate Binary Search Tree

Given a binary tree, determine if it is a valid binary search tree (BST). Assume a BST is defined as follows: The left subtree of a node contains only nodes with keys less than the node's key. The right subtree of a node contains only nodes with keys

【leetcode刷题笔记】Sudoku Solver

Write a program to solve a Sudoku puzzle by filling the empty cells. Empty cells are indicated by the character '.'. You may assume that there will be only one unique solution. A sudoku puzzle... ...and its solution numbers marked in red. 题解:递归.在每个空位

【leetcode刷题笔记】Maximum Depth of Binary Tree

Given a binary tree, find its maximum depth. The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node. 题解:递归,树的高度 = max(左子树高度,右子树高度)+1: 代码如下: 1 /** 2 * Definition for binary tree 3 * public cla