#defination of listNode
class ListNode:
def __init__(self,x):
self.val=x
self.next=None
class Solution:
def reverselist(self,head):
cur,prev=head,None
while cur:
cur.next,prev,cur=prev,cur,cur.next
return prev
def hascylce(self,head):
fast=slow=head
while slow.next and fast and fast.next:
slow=slow.next
fast=fast.next.next
if slow==fast:
return True
return False
#1 2 3 4 -->2 1 4 3
def swapPairs(self,head):
prev,prev.next=self,head
print(self.next.val)
while prev.next and prev.next.next:
a=prev.next
b=a.next
prev.next,b.next,a.next=b,a,b.next
prev=a
return self.next
if __name__=="__main__":
head=ListNode(1)
head.next=ListNode(2)
head.next.next=ListNode(3)
# head.next.next.next=head
su=Solution()
prev=su.reverselist(head)
# print(prev.val,prev.next.val,prev.next.next.val)
# print(su.hascylce(head))
print(su.swapPairs(head))```
python判断链表有环、翻转链表、链表交换相邻元素
最新推荐文章于 2024-07-20 12:30:43 发布