Created
April 15, 2014 23:43
Reverse Nodes in k-Group @leetcode
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package leetcode.linkedlist; | |
/** | |
* Solution: 拆分group, 每个group上reverse, 思路并不难,但是实现起来挺麻烦, | |
* 每一段需要currentHead, currentTail 做标记用于后面的链接. 还有preTail. 另外reverse过程中需要preNode和nextNode | |
* 有时候忘记这些flag就不容易一下子写出来,所以要按功能记,reverse需要2个,连接时候需要3个. | |
* @author jeffwan | |
* @date Apr 15, 2014 | |
*/ | |
public class ReverseKGroup { | |
public ListNode reverseKGroup(ListNode head, int k) { | |
if (head == null || k <= 1) { | |
return head; | |
} | |
int length = getLength(head); | |
int group = length / k; | |
if (group == 0) { | |
return head; | |
} | |
ListNode current = head; | |
ListNode preTail = null, currentHead = null, currentTail = null; | |
ListNode preNode = null, nextNode = null; | |
for (int i = 0; i < group; i++) { | |
preNode = null; | |
for (int j = 0; j < k; j++) { | |
// Reverse | |
if (current != null) { | |
nextNode = current.next; | |
current.next = preNode; | |
preNode = current; | |
} | |
// Assign currentHead, currentTail for future concatenate. | |
if (j == 0) { | |
currentTail = current; | |
} | |
if (j == k - 1) { | |
currentHead = current; | |
} | |
current = nextNode; | |
} | |
if (preTail == null) { | |
head = currentHead; | |
} else { | |
preTail.next = currentHead; | |
} | |
preTail = currentTail; | |
} | |
currentTail.next = current; | |
return head; | |
} | |
public int getLength(ListNode head) { | |
int length = 0; | |
while (head != null) { | |
head = head.next; | |
length++; | |
} | |
return length; | |
} | |
class ListNode { | |
int val; | |
ListNode next; | |
ListNode (int x) { this.val = x; } | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment