题目

Given a linked list, reverse the nodes of a linked list k at a time and return its modified list.

k is a positive integer and is less than or equal to the length of the linked 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

翻译

相比 swap in pairs,这道题是每满 k 个进行一次倒转,如果最终不满 k 个则不进行倒转

Hints

Related Topics: Linked List

solution

可以利用递归,递归函数传入 head 和 k,和 swap in pairs 一样,只是先对 k 个进行判断,看是否到达链表的最后,如果是最后 k-1 个(或者少于k-1),则不进行倒转,返回 head;然后对由 head 开始的 k 个 Node 组成的小链表进行倒转就好了,倒转可以参考 看图理解单链表的反转 只不过 head.next 不指向 null,而是指向递归的 reverseKGroup(end,k) (end 是 head 之后的第 k+1 个)

如果不利用递归其实也是一样的,只不过把递归的过程用 while 循环写出来,每到可以整除 k 的时候进行一次倒转

代码

Java

//without recursion
class Solution {
public ListNode reverseKGroup(ListNode head, int k) {
ListNode begin;
if (head==null || head.next ==null || k==1)
return head;
ListNode dummyhead = new ListNode(-1);
dummyhead.next = head;
begin = dummyhead;
int i=0;
while (head != null){
i++;
if (i%k == 0){
begin = reverse(begin, head.next);
head = begin.next;
} else {
head = head.next;
}
}
return dummyhead.next;
}
public ListNode reverse(ListNode begin, ListNode end){
ListNode curr = begin.next;
ListNode next, first;
ListNode prev = begin;
first = curr;
while (curr!=end){
next = curr.next;
curr.next = prev;
prev = curr;
curr = next;
}
begin.next = prev;
first.next = curr;
return first;
}
} //solution in discuss
class Solution {
public ListNode reverseKGroup(ListNode head, int k) {
ListNode curr = head;
int count = 0;
while (curr != null && count != k) { // find the k+1 node
curr = curr.next;
count++;
}
if (count == k) { // if k+1 node is found
curr = reverseKGroup(curr, k); // reverse list with k+1 node as head
// head - head-pointer to direct part,
// curr - head-pointer to reversed part;
while (count-- > 0) { // reverse current k-group:
ListNode tmp = head.next; // tmp - next head in direct part
head.next = curr; // preappending "direct" head to the reversed list
curr = head; // move head of reversed part to a new node
head = tmp; // move "direct" head to the next node in direct part
}
head = curr;
}
return head;
}
}

Python

# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None class Solution(object):
def reverseKGroup(self, head, k):
"""
:type head: ListNode
:type k: int
:rtype: ListNode
"""
tmp = head
if k<=1:
return head
for i in range(k):
if tmp!=None:
tmp = tmp.next
else:
return head
p = head
q = head.next
r = None
head.next = self.reverseKGroup(tmp,k)
while q!=tmp:
r = q.next
q.next = p
p = q
q = r
head = p
return head

最新文章

  1. MSCRM CRM 获取PickList 字段值函数解决方案
  2. LruCache缓存
  3. 英文分词算法(Porter stemmer)
  4. 3. javacript高级程序设计-基本概念
  5. 64位Eclipse运行时提示&ldquo;Failed to load the JNI shared library \Java\jre6\bin\client\jvm.dll&rdquo;的一个解决方案
  6. GDB---Oracle Function Call List
  7. Notes of the scrum meeting(11/1)
  8. .net项目的svn Global ignore pattern
  9. 8天玩转并行开发——第一天 Parallel的使用
  10. [Ruby on Rails Issue] When Setting Sqlite version on the Gemfile, Show error &quot;An error occurred while installing sqlite3 &quot;,
  11. codeforces 617E. XOR and Favorite Number 莫队
  12. Java程序猿的JavaScript学习笔记(3——this/call/apply)
  13. javascript动画效果之多物体透明度
  14. API设计相关
  15. 搭建gogs常见问题
  16. BZOJ3772 精神污染 主席树 dfs序
  17. SharePoint列表数据清除
  18. feginclinet中设置hystrix的参数
  19. JSDoc 3 生成javascript API文档
  20. 回顾RAC安装过程中对ASM的处理

热门文章

  1. PHP+Hadoop+Hive+Thrift+Mysql实现数据统计分析
  2. 【webGL】
  3. Hibernate-validator校验框架使用
  4. OpenCV——Brisk特征检测、匹配与对象查找
  5. Arduino入门笔记(2):Arduino的开发和virtualbreadboard仿真环境
  6. 蓝桥杯 历届试题 网络寻路(dfs搜索合法路径计数)
  7. mysql show profiles 使用分析sql 性能
  8. WPF listview Test Message list
  9. 【第六课】Nginx常用配置下详解
  10. Selenium-Switch与SelectApi接口详解