给定一个单链表的头节点 head,实现一个调整单链表的函数,使得每K个节点之间为一组进行逆序,并且从链表的尾部开始组起,头部剩余节点数量不够一组的不需要逆序。(不能使用队列或者栈作为辅助)
例如:链表:1->2->3->4->5->6->7->8->null, K = 3。那么 6->7->8,3->4->5,1->2各位一组。调整后:1->2->5->4->3->8->7->6->null。其中 1,2不调整,因为不够一组。
local t = {
next = nil,
data = 1,
}
local tt = t;
local max = 8;
while(max > 0) do
local t2 = {
next = nil,
data = 10 -max
}
tt.next = t2;
tt = t2;
max = max -1;
end
function revertTable( tab,limit )
-- 递归拆分子链
local tempHead = nil;
local tempHead2 = nil;
local tempK = 0
function revertSub(nextNode,fatherNode)
if nextNode == nil then
return
end
revertSub(nextNode.next,nextNode)
tempK = tempK +1;
-- print(nextNode.data,tempK);
if tempK == limit then
nextNode.next = tempHead2
tempHead2 = tempHead
tempHead = nil ;
tempK = 0
elseif tempK == 1 then
tempHead = nextNode
nextNode.next = fatherNode
else
nextNode.next = fatherNode
end
end
revertSub(tab,nil)
if tempHead ~= nil then
print('==========')
local max = 10
local tempNext = tempHead.next
local tempNext2 = nil
tempHead.next = tempHead2;
while tempNext and max > 0 do
max = max - 1;
print('2222======= ',tempHead.data)
tempNext2 = tempNext.next
tempNext.next = tempHead
tempHead = tempNext;
tempNext = tempNext2
end
else
tempHead = tempHead2
end
return tempHead
end
local head = revertTable(t,3);
local k = 20
while(head and k > 0)
do
k = k -1;
print(head.data);
head = head.next;
end