Implementé dos iteraciones y recursiones. El
problema es relativamente simple: la
lista original vinculada es
1-> 2-> 3-> 4-> 5-> NULL, y
después de la operación es
5-> 4-> 3-> 2-> 1-> NULL
Preste atención a esta pregunta: no olvide establecer el siguiente nodo de entrada original en Ninguno
Iteración:
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
if head is None:
return []
thisstack = []
print(thisstack)
while True:#head is not None:
thisstack.append(head)
#print(head.val)
if head.next is not None:
head = head.next#thisstack[-1]
else:
break
#print(thisstack)
tempnode = head#tempnode
while thisstack != []:
tempnode.next = thisstack.pop(-1)
tempnode = tempnode.next
tempnode.next = None
return head
Recursividad:
class Solution:
def __init__(self):
self.newhead = None
def reverseList(self, head: ListNode) -> ListNode:
if head is None:
return []
self.func(head)
head.next = None
return self.newhead
def func(self,node):
if node.next is not None:
self.func(node.next)
node.next.next = node
else:
self.newhead = node