题意:翻转链表
思路一:入栈出栈,利用数组模拟栈,入栈即每次在数组的开头加入数,出栈即从数组的开头开始
空间复杂度为O(n)
Runtime: 76 ms
思路二:头结点倒插,类似于思路一,原链表头结点依次插入新链表的开头,返回新链表
空间复杂度为O(1)
Runtime: 68 ms
思路三:递归!!!每一次递归返回的n中,需明白n指向返回的链表的头结点,这就是引入n的重要性
h和p仍为该循环所指向位置
空间复杂度为O(n^2)
Runtime: 72 ms
第一次:123 n=32,此步p指向2,返回321
第二次:23 n=3 此步p指向3,返回32
第三次:3 返回3
转载于:http://blog.youkuaiyun.com/coder_orz/article/details/51306985
思路一:
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def reverseList(self, head):
p=head
newList=[]
while p:
newList.insert(0,p.val)
p=p.next
p=head
for i in range(len(newList)):
p.val=newList[i]
p=p.next
return head
思路二:
class Solution(object):
def reverseList(self, head):
newhead=None
while head:
p=head
head=head.next
p.next=newhead
newhead=p
return newhead
思路三:
class Solution(object):
def reverseList(self, head):
if not head or not head.next:
return head
p=head.next
n=self.reverseList(p)
head.next=None
p.next=head
return n