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

LeetCode 206 Reverse a singly linked list.

时间:2016-12-15 11:58:04      阅读:144      评论:0      收藏:0      [点我收藏+]

标签:list   int   eve   递归   ever   hint   val   sed   imp   

Reverse a singly linked list.

Hint:

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

 递归的办法:

/**
 * 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 null;
        
        if(head.next==null)return head;
        
        ListNode p=head.next;
        ListNode n=reverseList(p);
        
        head.next=null;
        p.next=head;
        return n;
    }
}

 

非递归,迭代的办法:

if(head == null || head.next == null)
     return head; 
ListNode current =  head.next;
head.next = null;
while(current ! = null){
     ListNode temp = current.next;
     current.next = head;
     head = current;
    current = temp.next;
}
return head;

 

LeetCode 206 Reverse a singly linked list.

标签:list   int   eve   递归   ever   hint   val   sed   imp   

原文地址:http://www.cnblogs.com/blackiesong/p/6182335.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!