# 【Leetcode】Reverse Nodes in k-Group

371人阅读 评论(0)

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

	public ListNode reverseKGroup(ListNode head, int k) {
for (int i = 1; (i + k - 1) <= length; i += k) {
}
}

int length = 0;
while (p != null) {
length++;
p = p.next;
}
return length;
}

public ListNode reverseBetween(ListNode head, int m, int n) {
return null;
m = m - 1;
while (m-- > 0)// 因为start是从头结点开始算，所以要多走一步，即m--，而不是像下面的--n
start = start.next;
while (--n > 0)
rear = rear.next;
end = rear.next;
ListNode p = head, q, t;
q = p.next;
while (p != rear) {
t = q.next;
q.next = p;
p = q;
q = t;
}
// ===
start.next = rear;
}

0
0

个人资料
• 访问：568861次
• 积分：8674
• 等级：
• 排名：第2678名
• 原创：305篇
• 转载：6篇
• 译文：0篇
• 评论：37条
博客专栏
 Leetcode题解java版 文章：289篇 阅读：490928
文章分类
阅读排行
最新评论