美文网首页LeetCode
LeetCode刷题之Reverse Linked List

LeetCode刷题之Reverse Linked List

作者: JRTx | 来源:发表于2017-09-24 23:10 被阅读0次
    Problem

    Reverse a singly linked list.

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

    My Solution

    /**
     * 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 p = head, reverse = new ListNode(0);
            if (p == null) {
                return reverse.next;
            }
            ListNode q = new ListNode(p.val);
            reverse = insertHead(reverse, q);
            while (p.next != null) {
                p = p.next;
                q = new ListNode(p.val);
                reverse = insertHead(reverse, q);
            }
            return reverse.next;
        }
        
        public ListNode insertHead(ListNode reverse, ListNode node) {
            ListNode head = reverse;
            if (head.next == null) {
                head.next = node;
                node.next = null;
            } else {
                node.next = head.next;
                head.next = node;
            }
            return head;
        }
    }
    
    Great 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;
    }
    

    相关文章

      网友评论

        本文标题:LeetCode刷题之Reverse Linked List

        本文链接:https://www.haomeiwen.com/subject/wvglextx.html