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

lintcode 容易题:Reverse Linked List 翻转链表

时间:2015-10-18 16:53:02      阅读:357      评论:0      收藏:0      [点我收藏+]

标签:

题目:

翻转一个链表

样例

给出一个链表1->2->3->null,这个翻转后的链表为3->2->1->null

挑战

在原地一次翻转完成

解题:

递归还是可以解的

java程序:

技术分享
/**
 * Definition for ListNode.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int val) {
 *         this.val = val;
 *         this.next = null;
 *     }
 * }
 */ 
public class Solution {
    /**
     * @param head: The head of linked list.
     * @return: The new head of reversed linked list.
     */
    public ListNode reverse(ListNode head) {
        // write your code here
        if( head ==null || head.next ==null)
            return head;
        ListNode  second = head.next;
        head.next = null;
        ListNode res = reverse(second);
        second.next = head;
        return res;
    }
}
View Code

总耗时: 2079 ms

Python程序:

 

技术分享
"""
Definition of ListNode

class ListNode(object):

    def __init__(self, val, next=None):
        self.val = val
        self.next = next
"""
class Solution:
    """
    @param head: The first node of the linked list.
    @return: You should return the head of the reversed linked list. 
                  Reverse it in-place.
    """
    def reverse(self, head):
        # write your code here
        if head == None or head.next == None:
            return head 
        second = head.next;
        head.next = None 
        res = self.reverse(second)
        second.next = head
        return res
View Code

 

Python提交和上题一样一直Pending,应该是后台维护什么之类的。。。。。。。上面程序没有测试。

 

lintcode 容易题:Reverse Linked List 翻转链表

标签:

原文地址:http://www.cnblogs.com/theskulls/p/4889710.html

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