第一种:递归
public ListNode ReverseList(ListNode head) {
if(head==null ||head.next==null) return head;
ListNode sec=ReverseList(head.next);
head.next.next=head;
head.next=null;
return sec;
}第二种:循环(头插法)
public ListNode ReverseList(ListNode head) {
if(head==null ||head.next==null) return head;
ListNode pre=new ListNode(0);
pre.next=null;
while(head!=null){
ListNode temp =head.next;
head.next=pre.next;
pre.next=head;
head=temp;
}
return pre.next;
}
京公网安备 11010502036488号