leetcode 反转链表
从尾到头打印链表
http://www.nowcoder.com/questionTerminal/d0267f7f55b3412ba93bd35cfa8e8035
通过遍历将链表的值放入栈中(数组 append pop )然后再取出。注意 链表循环为l!=None
# -*- coding:utf-8 -*-
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
请在这里输入引用内容
class Solution:
# 返回从尾部到头部的列表值序列,例如[1,2,3]
def printListFromTailToHead(self, listNode):
# write code here
arraylist_temp=[]
arraylist=[]
l=listNode
while l!=None:
arraylist_temp.append(l.val)
l=l.next
print(arraylist_temp)
while arraylist_temp:
arraylist.append(arraylist_temp.pop())
return arraylist递归
class Solution:
# 返回从尾部到头部的列表值序列,例如[1,2,3]
def printListFromTailToHead(self, listNode):
# write code here
arraylist=[]
def print_list(l):
if l!=None:
print_list(l.next)
arraylist.append(l.val)
print_list(listNode)
return arraylist使用三个指针反转链表,其中cur最开始为head,其余最开始为None,next负责记住下一个节点,pre负责反转指向的节点
class Solution:
# 返回从尾部到头部的列表值序列,例如[1,2,3]
def printListFromTailToHead(self, listNode):
# write code here
if listNode==None:
return []
cur=listNode
pre=nextnode=None
while cur!=None:
nextnode=cur.next
cur.next=pre
pre=cur
cur=nextnode
head=pre
arraylist=[]
while head!=None:
arraylist.append(head.val)
head=head.next
return arraylist反转链表2
将链表分为两个部分,每次递归进行next部分的反转,然后将第一部分的next.next指向自己,将原有的next置为空(删除原有指针),改变头指针并返回,注意判断空链表,
class Solution:
# 返回从尾部到头部的列表值序列,例如[1,2,3]
def printListFromTailToHead(self, listNode):
# write code here
arraylist=[]
def reverse_list(listNode):
if listNode==None or listNode.next==None :
return listNode
head=reverse_list(listNode.next)
listNode.next.next=listNode
listNode.next=None#原有指针删除
return head
head=reverse_list(listNode)
while head!=None:
arraylist.append(head.val)
head=head.next
return arraylist
递归 前后指针
注意在判断cur.next时候 cur.next=pre
同时在使用的时候判断链表是否为空
class Solution:
# 返回从尾部到头部的列表值序列,例如[1,2,3]
def printListFromTailToHead(self, listNode):
# write code here
def reverse(cur,pre):
if cur.next==None:
cur.next=pre
return cur
nextnode=cur.next
cur.next=pre
# pre=cur
# cur=nextnode
head=reverse(nextnode,cur)
return head
def print_list(l):
arraylist=[]
while l!=None:
arraylist.append(l.val)
l=l.next
return arraylist
if listNode==None:
return []
result=reverse(listNode,None)
return print_list(result)
三奇智元机器人科技有限公司公司福利 50人发布