Tuesday, September 2, 2014

Reverse Nodes in k-Group

Problem

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

Idea

  • 每k个node是一个group
  • 采用递归的思路, 其中有3个重要的变量 head:当前group的头, nextGroupHead: 当前iteration, 下一个group的头, newNextGroupHead: 整理过的group的头,若下一个group不许要reverse则nextGroupHead和newNextGroupHead是一样的。
  • 每一次循环把当前group 倒过来即: 1->2->3->4 变成 1<-2<-3<-4 然后把1->next接到已经reverse的其他group前面

Solution


No comments:

Post a Comment