链表的建立:
首先建立节点:
class ListNode():
def __init__(self,value):
self.val=value
self.next=None
建立链表:
def createList(num):
if num<=0:
return None
head=None
val=0
node=None
while num>0:
if head is None:
head=ListNode(val) #为了保存head头节点的位置不变化
node=head
else:
node.next=ListNode(val)
node=node.next
val+=1
num-=1
return head
head=createList(5)
while head is not None:
print("{0}->".format(head.val),end=' ')
head=head.next
给定一个链表,旋转链表,将链表每个节点向右移动 k 个位置,其中 k 是非负数。
输入: 1->2->3->4->5->NULL, k = 2
输出: 4->5->1->2->3->NULL
解释: 向右旋转 1 步: 5->1->2->3->4->NULL
向右旋转 2 步: 4->5->1->2->3->NULL
思路:第一步建立节点。 第二步建立链表。 第三步,建立旋转函数。
旋转函数的思路为:将一个链表首尾相连。然后判断需要挪动的位置。把头指针放到挪动后的位置。这个时候需要注意的是,此时的链表仍然是首尾相连的。应该从头节点指针位置的地方断开。
class ListNode(): def __init__(self,value): self.val=value self.next=None #可以考虑先把链表变成一个环形 def xuanzhuan(head,K): p=head count=1 while p.next !=None: p=p.next count+=1 p.next=head K%=count #移动的位数 for i in range(count-K-1): head=head.next #断开 p=head head=head.next p.next=None return head def createList(num): if num<=0: return None head=None # val=0 val=1 node=None while num>0: if head is None: head=ListNode(val) #为了保存head头节点的位置不变化 node=head else: node.next=ListNode(val) node=node.next val+=1 num-=1 return head head=createList(5) p=head while p is not None: print("{0}->".format(p.val),end=' ') p=p.next print() head=xuanzhuan(head,2) while head is not None: print("{0}->".format(head.val),end=' ') head=head.next