//非递归方式进行链表反转 public ListNode reverseList(ListNode head){ if(head==null||head.next==null){ return head; }else { ListNode pre=head; ListNode p=head.next; ListNode next=null; while (p!=null) { next=p.next; p.next=pre; pre=p; p=next; } head.next=null; return pre; } }
//递归方式进行链表反转 public ListNode reverseListRecursive(ListNode head) { if(head==null||head.next==null){ return head; }else{ ListNode dot=recursive(head); head.next=null; return dot; } } public ListNode recursive(ListNode p){ if(p.next==null){ return p; }else{ ListNode next=p.next; ListNode dot=recursive(next); next.next=p; return dot; } }
时间: 2024-10-14 10:48:19