Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit40a5e0f

Browse files
author
applewjg
committed
Reverse Nodes in K group
Change-Id: I7b5de33afb6d2940ce74557a1c05779253eeda40
1 parent2fada19 commit40a5e0f

File tree

1 file changed

+57
-0
lines changed

1 file changed

+57
-0
lines changed

‎ReverseNodesinkGroup.java

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
/*
2+
Author: Andy, nkuwjg@gmail.com
3+
Date: Jan 18, 2015
4+
Problem: Reverse Nodes in k-Group
5+
Difficulty: Hard
6+
Source: https://oj.leetcode.com/problems/reverse-nodes-in-k-group/
7+
Notes:
8+
Given a linked list, reverse the nodes of a linked list k at a time and return its modified list.
9+
If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is.
10+
You may not alter the values in the nodes, only nodes itself may be changed.
11+
Only constant memory is allowed.
12+
For example,
13+
Given this linked list: 1->2->3->4->5
14+
For k = 2, you should return: 2->1->4->3->5
15+
For k = 3, you should return: 3->2->1->4->5
16+
17+
Solution: ...
18+
*/
19+
20+
/**
21+
* Definition for singly-linked list.
22+
* public class ListNode {
23+
* int val;
24+
* ListNode next;
25+
* ListNode(int x) {
26+
* val = x;
27+
* next = null;
28+
* }
29+
* }
30+
*/
31+
publicclassSolution {
32+
publicListNodereverseKGroup(ListNodehead,intk) {
33+
if (k <=1)returnhead;
34+
intT =GetLength(head) /k;
35+
ListNodedummy =newListNode(0),cur =head,ins =dummy;
36+
dummy.next =head;
37+
while ((T--) !=0) {
38+
for (inti =0;i <k -1; ++i) {
39+
ListNodemove =cur.next;
40+
cur.next =move.next;
41+
move.next =ins.next;
42+
ins.next =move;
43+
}
44+
ins =cur;
45+
cur =cur.next;
46+
}
47+
returndummy.next;
48+
}
49+
publicintGetLength(ListNodehead) {
50+
intlength =0;
51+
while (head !=null) {
52+
head =head.next;
53+
length++;
54+
}
55+
returnlength;
56+
}
57+
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp