码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode]: 206: Reverse Linked List

时间:2015-10-09 11:42:40      阅读:93      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!