反转部分链表python,反转python中的链表

I am asked to reverse a which takes head as parameter where as head is a linked list e.g.: 1 -> 2 -> 3 which was returned from a function already defined I tried to implement the function reverse_linked_list in this way:

def reverse_linked_list(head):

temp = head

head = None

temp1 = temp.next

temp2 = temp1.next

temp1.next = None

temp2.next = temp1

temp1.next = temp

return temp2

class Node(object):

def __init__(self,value=None):

self.value = value

self.next = None

def to_linked_list(plist):

head = None

prev = None

for element in plist:

node = Node(element)

if not head:

head = node

else:

prev.next = node

prev = node

return head

def from_linked_list(head):

result = []

counter = 0

while head and counter < 100: # tests don't use more than 100 nodes, so bail if you loop 100 times.

result.append(head.value)

head = head.next

counter += 1

return result

def check_reversal(input):

head = to_linked_list(input)

result = reverse_linked_list(head)

assert list(reversed(input)) == from_linked_list(result)

It is called in this way: check_reversal([1,2,3]). The function I have written for reversing the list is giving [3,2,1,2,1,2,1,2,1] and works only for a list of length 3. How can I generalize it for a list of length n?

解决方案

U can use mod function to get the remainder for each iteration and obviously it will help reversing the list . I think you are a student from Mission R and D

head=None

prev=None

for i in range(len):

node=Node(number%10)

if not head:

head=node

else:

prev.next=node

prev=node

number=number/10

return head

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值