/** * Definition for singly-linked list. * type ListNode struct { * Val int * Next *ListNode * } */funcreversePrint(head*ListNode)(ans[]int){for;head!=nil;head=head.Next{ans=append(ans,head.Val)}fori,j:=0,len(ans)-1;i<j;i,j=i+1,j-1{ans[i],ans[j]=ans[j],ans[i]}return}
/** * Definition for singly-linked list. * public class ListNode { * public int val; * public ListNode next; * public ListNode(int val=0, ListNode next=null) { * this.val = val; * this.next = next; * } * } */publicclassSolution{publicint[]ReversePrint(ListNodehead){List<int>ans=newList<int>();for(;head!=null;head=head.next){ans.Add(head.val);}ans.Reverse();returnans.ToArray();}}
1 2 3 4 5 6 7 8 910111213141516171819202122
/* public class ListNode {* public var val: Int* public var next: ListNode?* public init(_ val: Int) {* self.val = val* self.next = nil* }* }*/classSolution{funcreversePrint(_head:ListNode?)->[Int]{varstack=[Int]()varcurrent=headwhileletnode=current{stack.append(node.val)current=node.next}returnstack.reversed()}}
方法二:递归
我们可以使用递归的方式,先递归得到 head 之后的节点反过来的值列表,然后将 head 的值加到列表的末尾。
时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 为链表的长度。
1 2 3 4 5 6 7 8 91011121314
# Definition for singly-linked list.# class ListNode:# def __init__(self, x):# self.val = x# self.next = NoneclassSolution:defreversePrint(self,head:ListNode)->List[int]:ifheadisNone:return[]ans=self.reversePrint(head.next)ans.append(head.val)returnans
1 2 3 4 5 6 7 8 91011121314151617181920212223
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */classSolution{publicint[]reversePrint(ListNodehead){intn=0;ListNodecur=head;for(;cur!=null;cur=cur.next){++n;}int[]ans=newint[n];cur=head;for(;cur!=null;cur=cur.next){ans[--n]=cur.val;}returnans;}}
/** * Definition for singly-linked list. * type ListNode struct { * Val int * Next *ListNode * } */funcreversePrint(head*ListNode)(ans[]int){ifhead==nil{return}ans=reversePrint(head.Next)ans=append(ans,head.Val)return}