206. Reverse Linked List (Easy)

https://leetcode.com/problems/reverse-linked-list/

Reverse a singly linked list.

Example:

Input: 1->2->3->4->5->NULL
Output: 5->4->3->2->1->NULL

Follow up:

A linked list can be reversed either iteratively or recursively. Could you implement both?

Solutions

class Solution {
    public ListNode reverseList(ListNode head) {
        ListNode prev = null;
        ListNode curr = head;

        while (curr != null) {
            ListNode nextTemp = curr.next;
            curr.next = prev;
            prev = curr;
            curr = nextTemp;
        }

        return prev;
    }
}
class Solution {
    public ListNode reverseList(ListNode head) {
        if (head == null) {
            return null;
        }

        ListNode dummpy = new ListNode(-1);

        ListNode ptrA = head;
        ListNode ptrB = head.next;
        while(ptrA != null) {
            add(dummpy, ptrA);

            ptrA = ptrB;
            if (ptrB != null) {
                ptrB = ptrB.next;
            }
        }

        return dummpy.next;
    }

    private void add(ListNode head, ListNode node) {
        node.next = head.next;
        head.next = node;
    }
}

Incorrect Solutions

References

Copyright © iovi.com 2017 all right reserved,powered by GitbookLast Modification: 2019-12-03 11:01:17

results matching ""

    No results matching ""