Offer to prove safety of the programming problem (Java implementation) - reverse list

Title Description

After entering a list inverted list, the new list of the output header.

A thought

Iterative interpolation method using inverted head

achieve

/*
public class ListNode {
    int val;
    ListNode next = null;

    ListNode(int val) {
        this.val = val;
    }
}*/
public class Solution {
    public ListNode ReverseList(ListNode head) {
        ListNode newHead = new ListNode(-1);
        while(head != null){
            ListNode tmp = head.next;
            head.next = newHead.next;
            newHead.next = head;
            head = tmp;
        }
        return newHead.next;
    }
}

Ideas two

Recursion

achieve

public ListNode ReverseList(ListNode head) {
    if (head == null || head.next == null)
        return head;
    ListNode next = head.next;
    head.next = null;
    ListNode newHead = ReverseList(next);
    next.next = head;
    return newHead;
}

 

Guess you like

Origin www.cnblogs.com/MWCloud/p/11323016.html