我通过做作业来学习链表,并且制作链表的代码工作得很好。但是,操纵它是不正常的。所以,我有一个带有头的链表,我创建了一个函数,它接受两个参数(头,你想在第一个数字中添加多少个最后的数字)。这个函数的目的是,假设你有一个链表。1→4→5→6→2→3→9我想把最后三个数字放在第一个数字上,剩下的前4个数字放在这三个数字的最后一个,像这样。2→3→9→1→4→5→6所以,我需要做的是打破2和它之前的数字(I)之间的联系。E, 6)和链接6。在None旁边,然后连接9。在1旁边,得到想要的结果。但是,我在代码中有一些问题,它运行无限的时间和一点错误。你能帮我查一下这个吗?谢谢你
class Node: # Class will intantiate a node object
def __init__(self, data):
self.data = data # node have a data
self.next = None # node have a link as well ( of the next node), which is None currently.
<标题>def typeinput(a):
lis = [int(ele) for ele in a.split()]
head = None
tail = None
count = 0
for curele in lis:
if curele == -1:
break
newnode = Node(curele)
if head is None:
head = newnode
tail = newnode
else:
tail.next = newnode
tail = newnode
return head
<标题>def printll(head):
while head is not None:
print(str(head.data) + "->", end="")
head = head.next
print("None")
<标题>def length(head): # This function is used for determining the lenght of the Linked List
c = 0
while head is not None:
c += 1
head = head.next
return c
<标题>def appendN(head, n):
count = length(head) - n #it will give me the index of first last digit we want to break and append on first.
i = 0
tail = head #we don't want to change head so, we made a tail which will keep increasing till i<count.
if count < 0 or count > length(head): #if count less than 0 or greater than length
print(f"Please enter the number between 0 to {length(head)}")
return
while i < count: #loop run until we reach previous of the first last no. we want to append
tail = tail.next
i += 1
headT = tail #as we find that number we assigned it to new head
tail.next = None #this tail.next is of head so we make it None
while headT.next is not None: # we will make loop and assign the head to the last numbers.next
headT = headT.next
headT.next = head
return headT
<标题>lis = "9 8 7 7 6 5 4 3 3 2 1"
head = typeinput(lis)
c = appendN(head, 3)
printll(c)
我希望你能明白我在这里想做什么
标题>标题>标题>标题>标题>您可能想尝试下面这样的另一个实现。请注意,这段代码甚至适用于负整数n
值,因此如果您输入-3作为参数,则LinkedList将向相反方向移动,避免问题和异常:
def appendN(head, n):
if not head:
return
size = 1
tail = head
while tail.next:
size += 1
tail = tail.next
tail.next = head
for i in range(-n % size):
tail = tail.next
head = tail.next
tail.next = None
return head
你可以做你正在尝试的操作(我称之为右旋转,而不是"追加"),通过跟踪你在列表中一起前进的两个节点引用,n
节点分开。
def appendN(head, n):
tail = new_tail = head # initialize two references into the list
for _ in range(n): # advance the first one n times
if not tail.next:
raise ValueError("Linked list is too short") # or print and return
tail = tail.next
while tail.next: # then advance both in lockstep until you reach the end
tail = tail.next
new_tail = new_tail.next
tail.next = head # link the end of the list to the beginning
head = new_tail.next # grab a reference to the new head
new_tail.next = None # and split the list where the second reference ended up
return head