我希望用Python做到这一点。而且我不想反向打印它,但实际上是反转给定的节点。我已经看到它用其他语言完成,但很难在Python中找到一个例子。
我试图在一个函数中执行此操作,但如果需要辅助函数那么就可以了。
答案 0 :(得分:13)
def reverse (item, tail = None):
next = item.next
item.next = tail
if next is None:
return item
else:
return reverse(next, item)
使用这样一个简单的链表实现:
class LinkedList:
def __init__ (self, value, next = None):
self.value = value
self.next = next
def __repr__ (self):
return 'LinkedList({}, {})'.format(self.value, repr(self.next))
示例:
>>> a = LinkedList(1, LinkedList(2, LinkedList(3, LinkedList(4))))
>>> a
LinkedList(1, LinkedList(2, LinkedList(3, LinkedList(4, None))))
>>> b = reverse(a)
>>> b
LinkedList(4, LinkedList(3, LinkedList(2, LinkedList(1, None))))
>>> a # note that there is a new head pointer now
LinkedList(1, None)
答案 1 :(得分:3)
我使用递归的反向方法创建了链表的简单实现。
class Node(object):
def __init__(self,initdata):
self.data = initdata
self.next = None
class LinkedList(object):
def __init__(self):
self.head = None
def isEmpty(self):
return self.head == None
def add(self,data): #this method adds node at head
temp = Node(data)
temp.setNext(self.head)
self.head = temp
def traverse(self):
current = self.head
while current:
if current.getNext():
print(current.data,end="->")
else:
print(current.data)
current = current.getNext()
def reverse(self,item):
if item.next == None:
self.head = item
return
self.reverse(item.next)
temp = item.next
temp.next = item
item.next = None
def main():
mylist = LinkedList()
mylist.add(15)
mylist.add(20)
mylist.add(25)
mylist.add(30)
mylist.traverse()
mylist.reverse(mylist.head)
mylist.traverse()
print(mylist.head.data)
if __name__ == "__main__":
main()
输出:
Before:
30->25->20->15
After:
15->20->25->30
答案 2 :(得分:0)
使用递归的另一种方法:
def reverse(head):
# Empty list is always None
if not head:
return None
# List of length 1 is already reversed
if not head.get_next():
return head
next = head.get_next()
head.set_next(None)
rest = reverse(next)
next.set_next(head)
return rest
答案 3 :(得分:0)
对@Rajat Bhatt实现的轻微修改。区别在于下面的代码可以作为链表类之外的单独函数执行。
print '\n-- Initialize --'
lst = LinkedList(10) # 10 --> *
print '\n-- Insert --'
lst.append(20) # 10 --> 20 --> *
lst.append(30) # 10 --> 20 --> 30 --> *
lst.insertAt(15, pos=1) # 10 --> 15 --> 20 --> 30 --> *
lst.insertAt(25, pos=3) # 10 --> 15 --> 20 --> 25 --> 30 --> *
lst.insertAt(2) # 2 --> 10 --> 15 --> 20 --> 25 --> 30 --> *
lst.append(100) # 2 --> 10 --> 15 --> 20 --> 25 --> 30 --> 100 --> *
lst.append(500) # 2 --> 10 --> 15 --> 20 --> 25 --> 30 --> 100 --> 500 --> *
print lst
# 2 --> 10 --> 15 --> 20 --> 25 --> 30 --> 100 --> 500 --> *
print '\n-- Reverse using Recursion --'
def revFunc(curr):
if curr.next_node is None:
lst.head = curr
return None
revFunc(curr.next_node)
curr.next_node.next_node = curr
curr.next_node = None
revFunc(lst.head)
print lst
# Head --> 500 --> 100 --> 30 --> 25 --> 20 --> 15 --> 10 --> 2 --> *
答案 4 :(得分:0)
def reverse_list(self,node):
if node is None:
return //list is empty
elif node.next is None:
self.head = node // changing the head to last node after reversal
return
else:
reverse_list(node.next) //call the function recursively until the end of the list
node.next.next = node //reverse the link
node.next = None
答案 5 :(得分:0)
寻求彻底了解如何使用迭代和递归方法在python中反向链接列表,并进行适当的重构后,我对此进行了编码。我研究过的许多链接似乎不清楚或有不必要的步骤。如果我还没有达到最低限度/清晰的步骤,那么我认为这些步骤至少已经接近。我觉得最好不要包含输出,但是它将按原样运行并产生输出(python 2.7并易于为3.x修改)。
class Node:
def __init__(self,val):
self.val = val
self.next = None # the pointer initially points to nothing
def traverse(self):
# start from the head node
node = self
while node != None:
# access the node value
out_string = 'val = %d, loc = %s, next = %s'
print out_string % (node.val, node, node.next)
# move on to the next node
node = node.next
def reverse_iteratively(self):
previous = None
current = None
head = self
while head:
# before reverse
previous = current
current = head
head = head.next
# reverse the link
current.next = previous
def reverse_recursively(self, node, pre=None):
if node.next != None:
self.reverse_recursively(node.next, pre=node)
node.next = pre
### Operation Section
node0 = Node(0)
node1 = Node(7); node0.next = node1
node2 = Node(14); node1.next = node2
node3 = Node(21); node2.next = node3
node4 = Node(28); node3.next = node4
node5 = Node(35); node4.next = node5
node6 = Node(42); node5.next = node6
node7 = Node(49); node6.next = node7
node8 = Node(56); node7.next = node8
node9 = Node(63); node8.next = node9
print "Forward linked:"
node0.traverse()
node0.reverse_recursively(node0)
print "Reverse linked:"
node9.traverse()
答案 6 :(得分:0)
def reverse_ll_pass(self):
temp = self.head
if temp is None:
return
return self.reverse_ll_recursive(temp,past=None)
def reverse_ll_recursive(self,curr,past):
if curr is None:
self.head = past
return self.head
else:
future = curr.next
curr.next = past
past = curr
curr = future
return self.reverse_ll_recursive(curr,past)
答案 7 :(得分:0)
与poke的解决方案非常相似,但我更喜欢先考虑基本情况:
uint8_t was_cr = 0;
void terminal_putchar(char c)
{
/* turn LF -> CRLF if missing CR */
if (c == '\n' && !was_cr) {
terminal_putentryat('\r', terminal_color, terminal_column, terminal_row);
}
/* at this point was_cr has already been read */
/* considering that was_cr is read every time this function is called, */
/* it is likely that the CPU will cache it's value, so read times will be short */
/* even if it isn't cached, memory reads are always faster than memory writes */
if (c == '\r' && !was_cr) was_cr = 1;
else if (was_cr) was_cr = 0;
terminal_putentryat(c, terminal_color, terminal_column, terminal_row);
if (++terminal_column == VGA_WIDTH) {
terminal_column = 0;
if (++terminal_row == VGA_HEIGHT)
terminal_row = 0;
}
}