常规解法(递归)
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ class Solution { ArrayList<Integer> list=new ArrayList(); public ListNode reverseList(ListNode head) { rec(head); ListNode p=head; int len=list.size(); for(int i=0;i<len;i++) { p.val=list.get(i); p=p.next; } return head; } void rec(ListNode head){ ListNode p=head; if(p==null)return; else rec(p.next); list.add(p.val); } }
原地反转(时空复杂度都有很大提高)
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ class Solution { public ListNode reverseList(ListNode head) { ListNode pre=null; ListNode cur=head; while(cur!=null) { ListNode temp=cur.next; cur.next=pre; pre=cur; cur=temp; } return pre; } }
浙公网安备 33010602011771号