Leetcode练习(Python):链表类:第206题:反转链表:反转一个单链表。
题目:
反转链表:反转一个单链表。
进阶:
你可以迭代或递归地反转链表。你能否用两种方法解决这道题?
你可以迭代或递归地反转链表。你能否用两种方法解决这道题?
思路:
思路一:使用栈的思想。
思路二:使用迭代。
思路三:使用递归。
程序1:
# 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 not head:
return None
myStack = list()
myNode = head
while myNode:
myStack.append(myNode.val)
myNode = myNode.next
myNewHead = ListNode(myStack.pop())
myNode2 = myNewHead
while len(myStack):
myNode2.next = ListNode(myStack.pop())
myNode2 = myNode2.next
#myNode2.next = null
return myNewHead
程序2:
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
if not head:
return None
index1 = head
while index1.next:
index2 = ListNode(index1.next.val)
index2.next = head
head = index2
index1.next = index1.next.next
return head
程序3:
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
if head == None or head.next == None:
return head
newListNode = self.reverseList(head.next)
head.next.next = head
head.next = None
return newListNode