k个一组翻转链表python_【python-leetcode25-翻转链表】K 个一组翻转链表

问题描述:

给你一个链表,每 k 个节点一组进行翻转,请你返回翻转后的链表。

k 是一个正整数,它的值小于或等于链表的长度。

如果节点总数不是 k 的整数倍,那么请将最后剩余的节点保持原有顺序。

示例 :

给定这个链表:1->2->3->4->5

当 k = 2 时,应当返回: 2->1->4->3->5

当 k = 3 时,应当返回: 3->2->1->4->5

说明 :

你的算法只能使用常数的额外空间。

你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。

方法一:利用栈(不过空间复杂度为O(k))

过程:

一次循环之后:

第二次循环过后:

第三次循环:由于tmp==None,此时count=,因此直接将p.next指向head。最后返回newhead.next即可。

代码:

classListNode:def __init__(self,x):

self.val=x

self.next=None

n1=ListNode(1)

n2=ListNode(2)

n3=ListNode(3)

n4=ListNode(4)

n5=ListNode(5)

n6=ListNode(6)

n7=ListNode(7)

n1.next=n2;n2.next=n3;n3.next=n4;n4.next=n5defprintListNode(head):while head !=None:print(head.val)

head=head.next#printListNode(n1)

classSolution:defreverseKGroup(self, head,k):

newhead=ListNode(0)

p=newheadwhileTrue:

count=k

stack=[]

tmp=headwhile count andtmp:

stack.append(tmp)

tmp=tmp.next

count-= 1

ifcount :

p.next=headbreak

whilestack:

p.next=stack.pop()

p=p.next

head=tmpreturnnewhead.next

s=Solution()

t=s.reverseKGroup(n1,2)

printListNode(t)

方法二:尾插法

初始化:

进入第一次循环:

进入第二次循环:

依次类推。

再比如:[1,2,3,4,5,6,7],k=3,过程也就是:

[2,3,1,4,5,6,7]

[3,2,1,4,5,6,7]

[3,2,1,5,6,4,7]

[3,2,1,6,5,4,7]

#Definition for singly-linked list.#class ListNode:#def __init__(self, x):#self.val = x#self.next = None

classSolution:def reverseKGroup(self, head: ListNode, k: int) ->ListNode:

newhead=ListNode(0)

newhead.next=head

pre=newhead

tail=newheadwhileTrue:

count=kwhile count andtail:

count-= 1tail=tail.nextif not tail: breakhead=pre.nextwhile pre.next !=tail:

cur= pre.next #获取下一个元素

#pre与cur.next连接起来,此时cur(孤单)掉了出来

pre.next =cur.next

cur.next= tail.next #和剩余的链表连接起来

tail.next = cur #插在tail后面

#改变 pre tail 的值

pre =head

tail=headreturn newhead.next

方法三:递归,理解不了

classSolution:defreverseKGroup(self, head,k):

cur=head

count=0while cur and count!=k:

cur=cur.next

count+= 1

if count ==k:

cur=self.reverseKGroup(cur, k)print("cur.val=",cur.val)whilecount:print("head.val=",head.val)

tmp=head.next

head.next=cur

cur=head

head=tmp

count-= 1head=curreturn head

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值