Day61.算法训练

206. 反转链表

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode reverseList(ListNode head) {
        ListNode o1 = head;
        ListNode n1 = null;

        while (o1 != null) {
            ListNode temp = o1.next;
            o1.next = n1;

            n1 = o1;
            o1 = temp;
        }
        return n1;
    }
}

class Solution {
    public ListNode reverseList(ListNode head) {

        List o1 = new List(head);

        List o2 = new List(null);

        while (true) {
            ListNode listNode = o1.removeFirst();
            if (listNode == null) {
                break;
            }
            o2.addFirst(listNode);
        }
        return o2.head;
    }

    class List {

        private ListNode head;

        public List(ListNode head) {
            this.head = head;
        }

        public void addFirst(ListNode first) {
            first.next = head;
            head = first;
        }

        public ListNode removeFirst() {
            ListNode first = null;
            if (head != null) {
                first = this.head;
                this.head = this.head.next;
            }
            return first;
        }

    }
}

class Solution {
    public ListNode reverseList(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }
        ListNode listNode = reverseList(head.next);
        
        head.next.next = head;
        head.next = null;
        return listNode;
    }
}

class Solution {
    public ListNode reverseList(ListNode head) {
        if (head == null) {
            return null;
        }
        ListNode n1 = head;
        ListNode o1 = head;
        ListNode o2 = head.next;

        while (o2 != null) {
            o1.next = o2.next;
            o2.next = n1;
            n1 = o2;
            o2 = o1.next;
        }
        return n1;
    }
}

你可能感兴趣的:(算法)