【发布时间】:2021-05-21 06:58:15
【问题描述】:
我正在尝试解决algoexpert 上的以下问题:
移位链表
编写一个函数,接收单链表的头部和一个整数
k,将列表移动到位(即,不创建全新的 list) byk位置,并返回其新头部。移动链表意味着向前或向后移动其节点并换行 他们在适当的地方围绕列表。例如,移动链表 向前移动一个位置会使它的尾巴成为链接的新头 列表。
节点是向前还是向后移动取决于是否
k是正数还是负数。每个
LinkedList节点都有一个整数value以及next节点指向列表中的下一个节点或None/null如果它是列表的尾部。你可以假设输入的链表总是至少有一个节点; 换句话说,头部永远不会是
None/null。示例输入
head = 0 -> 1 -> 2 -> 3 -> 4 -> 5 // the head node with value 0 k = 2样本输出
4 -> 5 -> 0 -> 1 -> 2 -> 3 // the new head node with value 4
问题给出的代码大纲如下:
class LinkedList: def __init__(self, value): self.value = value self.next = None def shiftLinkedList(head, k): #Write your code here. pass
我想我在链表上的背景非常有限,因为从我读过的链表上的每一个资源来看,它的概要都需要节点类,并且在 LinkedList 类中拥有所有旋转或移动的方法.
我假设函数的 head 参数将是一个表示列表位置的整数,但是我如何将 head 引用回原始列表?我已经在 Thonny 编辑器中编写了代码,但我在 LinkedList 类中编写了函数,并在列出我的列表后简单地调用它。
例如:
class Node:
def __init__self(data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def push(self, newhead):
newnode = Node(new_data)
newnode.next = self.head
self.head = newnode
list1 = LinkedList()
list1.head = Node(1)
e2 = 2
e3 = 3
list1.head.next = e2
e2.next = e3
只有在我建立了我的链表后,我才能在类中创建一个方法来移动或旋转它。还是我错了?
我尝试按照算法想要的方式创建一个函数,但我仍然卡住了。我想我真正困惑的是参数head是整数还是LinkedList?
这是我的完整尝试:
class Node:
def __init__(self, data):
self.data = data #assign data
self.next = None #initialize next as null
class LinkedList:
#function to initalize the linked list object
def __init__(self):
self.head = None
def printList(self):
temp = self.head
while(temp):
print(temp.data)
temp = temp.next
def moveToFront(self):
tmp = self.head
sec_last = None
if not tmp or not tmp.next:
return
while tmp and tmp.next:
sec_last = tmp
tmp = tmp.next
sec_last.next = None
tmp.next = self.head
self.head = tmp
def shiftList(head, k):
if not head:
return
tmp = head
length = 1
while(temp.next != None):
tmp = tmp.next
length += 1
if(k>length):
k = k%length
k = length - k
if(k==0 or k==length):
return head
current = head
cmt = 1
while(cmt < k and current != None):
current = current.next
cmt += 1
if(current==None):
return head
kthnode = current
tmp.next = head
head = kthnode.next
kthnode.next = None
return head
【问题讨论】:
标签: python data-structures linked-list