标签:
题目:
翻转一个链表
给出一个链表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; } }
总耗时: 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
Python提交和上题一样一直Pending,应该是后台维护什么之类的。。。。。。。上面程序没有测试。
lintcode 容易题:Reverse Linked List 翻转链表
标签:
原文地址:http://www.cnblogs.com/theskulls/p/4889710.html