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

Commitc0746d1

Browse files
committed
reverse
1 parentb4483a3 commitc0746d1

File tree

1 file changed

+63
-10
lines changed

1 file changed

+63
-10
lines changed

‎list/ReverseKGroup.java

Lines changed: 63 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616
publicclassReverseKGroup {
1717
// Solution 1:
1818
// recursion.
19+
// 思路是先反转,如果发现长度不够K,再翻回来
1920
publicListNodereverseKGroup1(ListNodehead,intk) {
2021
if (head ==null) {
2122
returnnull;
@@ -24,16 +25,6 @@ public ListNode reverseKGroup1(ListNode head, int k) {
2425
returnrec(head,k);
2526
}
2627

27-
publicclassReturnType{
28-
ListNodehead;
29-
ListNodetail;
30-
31-
ReturnType(ListNodehead,ListNodetail) {
32-
this.head =head;
33-
this.tail =tail;
34-
}
35-
}
36-
3728
publicListNoderec(ListNodehead,intk) {
3829
ListNodedummy =newListNode(0);
3930

@@ -70,4 +61,66 @@ public ListNode rec(ListNode head, int k) {
7061

7162
returndummy.next;
7263
}
64+
65+
/*
66+
* Solution 2:
67+
* 使用区间反转的办法, iteration.
68+
* */
69+
publicListNodereverseKGroup(ListNodehead,intk) {
70+
if (head ==null) {
71+
returnnull;
72+
}
73+
74+
ListNodedummy =newListNode(0);
75+
dummy.next =head;
76+
77+
ListNodecur =head;
78+
ListNodepre =dummy;
79+
80+
intcnt =0;
81+
82+
while (cur !=null) {
83+
cnt++;
84+
if (cnt ==k) {
85+
cnt =0;
86+
pre =reverse(pre,cur.next);
87+
}
88+
cur =cur.next;
89+
}
90+
91+
returndummy.next;
92+
}
93+
94+
/**
95+
* Reverse a link list between pre and next exclusively
96+
* an example:
97+
* a linked list:
98+
* 0->1->2->3->4->5->6
99+
* | |
100+
* pre next
101+
* after call pre = reverse(pre, next)
102+
*
103+
* 0->3->2->1->4->5->6
104+
* | |
105+
* pre next
106+
* @param pre
107+
* @param next
108+
* @return the reversed list's last node, which is the precedence of parameter next
109+
*/
110+
privatestaticListNodereverse(ListNodepre,ListNodenext){
111+
ListNodecur =pre.next;
112+
113+
// record the new tail.
114+
ListNodelast =cur;
115+
while (cur !=next) {
116+
ListNodetmp =cur.next;
117+
cur.next =pre.next;
118+
pre.next =cur;
119+
cur =tmp;
120+
}
121+
122+
last.next =next;
123+
returnlast;
124+
}
125+
73126
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp