Share my two methods of 0ms java solution


  • 0
    C
    //1. directly swap
    public ListNode reverseList(ListNode head) {
    	if (head == null || head.next == null)
    		return head;
    	ListNode prepre = null, pre = head, p = head.next;
    	for (; p != null; prepre = pre, pre = p, p = p.next)
    		pre.next = prepre;
    	pre.next = prepre;
    	return pre;
    }
    //2.insert node before head when rebuliding linked-list
        public ListNode reverseList(ListNode head) {
        ListNode dummy = new ListNode(0);
        while(head!=null){
            ListNode temp = head.next;
            head.next = dummy.next;
            dummy.next = head;
            head = temp;
        }
        return dummy.next;
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.