首页 > 其他 > 详细

206. Reverse Linked List

时间:2016-09-10 08:57:48      阅读:201      评论:0      收藏:0      [点我收藏+]

Reverse a singly linked list.

Solution 1:

思路:null的使用。用一个null node来承接,一个一个接上去即可。一刷的时候还觉得这node转化好麻烦好神奇,熟悉之后其实做起来很快。

  

/**
 * 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 last=null;
        while(head!=null)
        {
            ListNode copy=head.next;
            head.next=last;
            last=head;
            head=copy;
        }
        return last;
        
    }
}

Solution 2: 

follow up : Use Recursion

思路:如果head.next不是null,递归head.next,注意先把head.next指针存好,方便于reverse之后接上head。因为返回的是一个listnode,用一个dummy node来把node用于输出。如果head.next是null的话,直接返回head即可。Recursion真的是一个神器!

/**
 * 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 dummy=new ListNode(-1);
        if(head.next!=null)
        {
            ListNode copy=head.next;
            dummy.next=reverseList(head.next);
            copy.next=head;
            head.next=null;
        }
        else
        {
            return head;
        }
        return dummy.next;
        
    }
}

 

206. Reverse Linked List

原文:http://www.cnblogs.com/Machelsky/p/5858680.html

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