基本上,我正在实现一个LinkedList类,然后实现各种方法来使用它。下面是 LinkedList 类(及其依赖的 Node 类(的代码
# A simple linked list implementation
class Node:
# attributes:
# data (can be anything)
# next (another Node)
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
# attributes:
# head (a Node)
# ****************
# methods:
# insert
# find
# delete
def __init__(self):
self.head = None
def __str__(self):
output = []
current_node = self.head
while current_node:
output.append(str(current_node.data))
current_node = current_node.next
return(", ".join(output))
# Creates a Node with the given data and inserts into the front of the list.
def insert(self, data):
new_node = Node(data)
new_node.next = self.head
self.head = new_node
# Finds the first node with the given data. Returns None if there is no such node.
def find(self, data):
current_node = self.head
while(current_node):
if (current_node.data == data):
return current_node
current_node = current_node.next
return None # We reached the end of the list without finding anything.
# Deletes given node. Can be used in conjunction with find.
def delete(self, deleted_node):
if deleted_node == self.head:
self.head = self.head.next
return
current_node = self.head
while(current_node.next != deleted_node):
current_node = current_node.next
current_node.next = deleted_node.next
然后,我正在尝试实现一个 rotate(my_list, N( 函数,它将my_list旋转 N。以下是我的代码:
import linkedlists as ll
from ErrorHandler import sanitize
import random, math, time, copy
def length(my_list):
sanitize(my_list, ll.LinkedList)
if my_list.head == None: return 0
count = 1 #First item! Ah, ah, ah
current_node = my_list.head
while current_node.next != None:
current_node = current_node.next
count += 1 #One more item! Ah, ah, ah
return count
def get_Nth(my_list, N):
sanitize(my_list, ll.LinkedList)
if my_list.head == None: return None
current_node = my_list.head
count = 0
while current_node.next != None:
if count == N:
return current_node
count +=1
current_node = current_node.next
return current_node
def rotate(my_list, N):
sanitize(my_list, ll.LinkedList)
if my_list.head == None: return None
N = N % length(my_list)
lent = length(my_list)
get_Nth(my_list, lent-1).next = my_list.head
my_list.head = get_Nth(my_list, lent-N)
get_Nth(my_list, lent-N-1).next = None
但是,在包含从 0 到 9 的数字(按升序排列(的 LinkedList 上调用 rotate(( 将返回 8,9,0,1,2,3,4,5。为什么?我很确定这与倒数第三行和倒数第二行有关,因为当在my_list.head旁边分配get_Nth(my_list,lent-1(.时,它只指向my_list.head,而不是当时my_list.head指向的Node对象。
我该如何解决这个问题?
你的错误就在这里:get_Nth(my_list, lent-N-1).next = None
我假设你打电话给rotate(my_list, 2)
所以在这一点上,列表看起来像这样[8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, ...]
.所以当你调用get_Nth(my_list, lent-N-1)
时,lent-N-1
是7,嗯,索引7处的元素实际上是5。
你应该只使用lent-1
.