美文网首页
206. Reverse Linked List

206. Reverse Linked List

作者: hyhchaos | 来源:发表于2016-11-28 23:09 被阅读8次

    Java

    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) { val = x; }
     * }
     */
    public class Solution {
        public ListNode reverseList(ListNode head) {
            if(head==null) return head;
            ListNode pre=null;
            ListNode cur=head;
            ListNode nt=head.next;
            while(cur.next!=null)
            {
                nt=cur.next;
                cur.next=pre;
                pre=cur;
                cur=nt;
            }
            cur.next=pre;
            head=cur;
            return head;
        }
    }
    

    Javascript

    /**
     * Definition for singly-linked list.
     * function ListNode(val) {
     *     this.val = val;
     *     this.next = null;
     * }
     */
    /**
     * @param {ListNode} head
     * @return {ListNode}
     */
    var reverseList = function(head) {
        if(head===null) return head;
            var pre=null;
            var cur=head;
            var nt=head.next;
            while(cur.next!==null)
            {
                nt=cur.next;
                cur.next=pre;
                pre=cur;
                cur=nt;
            }
            cur.next=pre;
            head=cur;
            return head;
    };
    

    优解,差不多

    注意头节点的指针要指向空

    相关文章

      网友评论

          本文标题:206. Reverse Linked List

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