首页 > 其他 > 详细

[LeetCode]: 206: Reverse Linked List

时间:2015-10-09 11:42:11      阅读:208      评论:0      收藏:0      [点我收藏+]

题目:

Reverse a singly linked list.

 

思路1:直接用循环遍历即可

 

代码:

    public static ListNode reverseList(ListNode head) {
        if(head == null || head.next == null){
            return head;
        }
        
        ListNode nodeCurrent = head.next;
        ListNode nodeLast= head;
        
        head.next = null;
        
        while(nodeCurrent != null){
            ListNode tempNode = nodeCurrent.next;
            nodeCurrent.next = nodeLast;
            nodeLast = nodeCurrent;
            nodeCurrent = tempNode;
        }
        
        return nodeLast;
    }

 

思路2:递归

    public static ListNode reverseList(ListNode head) {
        if(head == null || head.next == null){
            return head;
        }
        
        ListNode nodeCurrent = head.next;  
        ListNode nodeNext = reverseList(nodeCurrent);  
        
        head.next = null;  
        nodeCurrent.next = head;  
        
        return nodeNext;
    }

 

[LeetCode]: 206: Reverse Linked List

原文:http://www.cnblogs.com/savageclc26/p/4863130.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!