给出一个链表,每 k 个节点一组进行翻转,并返回翻转后的链表。k 是一个正整数,它的值小于或等于链表的长度。如果节点总数不是 k 的整数倍,那么将最后剩余节点保持原有顺序。
说明:
1. 你需要自行定义链表结构,将输入的数据保存到你的链表中;
2. 你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换;
3. 你的算法只能使用常数的额外空间。
输入描述:
第一行输入是链表的值 第二行输入是K的值,K是大于或等于1的整数 输入形式为: 1 2 3 4 5 2
输出描述:
当 k = 2 时,应当输出: 2 1 4 3 5 当 k = 3 时,应当输出: 3 2 1 4 5 当k=6时,应当输出: 1 2 3 4 5
输入例子1:
1 2 3 4 5 2
输出例子1:
2 1 4 3 5
示例代码:
# data structure
class LinkNode(object):
def __init__(self, val):
self.val = val
self.next = None
# create linklist
def create_link(link):
if not link:
return
p = head = LinkNode(link[0])
for i in link[1:]:
p.next = LinkNode(i)
p = p.next
return head
# print linklist
def print_link(head):
while head:
print(head.val, end=' ')
head = head.next
print()
# reverse linklist
def reverse_link(head, k):
p = new_head = LinkNode(0)
while True:
stack = []
count = k
tmp = head
while count and tmp:
stack.append(tmp)
tmp = tmp.next
count -= 1
if count:
p.next = head
break
while stack:
p.next = stack.pop()
p = p.next
head = tmp
return new_head.next
a = [1, 2, 3, 4, 5, 6]
obj = create_link(a)
print_link(obj)
result = reverse_link(obj, 4)
print_link(result)
运行效果:
示例代码2:
# data structure
class LinkNode(object):
def __init__(self, val):
self.val = val
self.next = None
# create linklist
def create_link(link):
if not link:
return
p = head = LinkNode(link[0])
for i in link[1:]:
p.next = LinkNode(i)
p = p.next
return head
# print linklist
def print_link(head):
while head:
print(head.val, end=' ')
head = head.next
print()
# reverse linklist
def reverse_link(head, k):
p = new_head = LinkNode(0)
while True:
stack = []
count = k
tmp = head
while count and tmp:
stack.append(tmp)
tmp = tmp.next
count -= 1
if count:
p.next = head
break
while stack:
p.next = stack.pop()
p = p.next
head = tmp
return new_head.next
a = [1, 2, 3, 4, 5, 6]
a = (input('请输入列表数据:'))
a = a.split()
k = int(input('请输入k:'))
obj = create_link(a)
print_link(obj)
result = reverse_link(obj, k)
print_link(result)
运行效果: