/** * Definition for singly-linked list. * type ListNode struct { * Val int * Next *ListNode * } */funcreverseList(head*ListNode)*ListNode{varpre*ListNodeforp:=head;p!=nil;{q:=p.Nextp.Next=prepre=pp=q}returnpre}
/** * Definition for singly-linked list. * public class ListNode { * public var val: Int * public var next: ListNode? * public init(_ val: Int) { * self.val = val * self.next = nil * } * } */classSolution{funcreverseList(_head:ListNode?)->ListNode?{varprev:ListNode?=nilvarcurrent=headwhilecurrent!=nil{letnext=current?.nextcurrent?.next=prevprev=currentcurrent=next}returnprev}}
方法二
1 2 3 4 5 6 7 8 910111213141516171819
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */classSolution{publicListNodereverseList(ListNodehead){if(head==null||head.next==null){returnhead;}ListNoderes=reverseList(head.next);head.next.next=head;head.next=null;returnres;}}