python--lintcode35. 翻转链表

描述

翻转一个链表

您在真实的面试中是否遇到过这个题?  

样例

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


基础题,思路就是用不同指针去做。直接给出代码吧:

class ListNode(object):

    def __init__(self, val, next=None):
        self.val = val
        self.next = next


class Solution:
    """
    @param head: n
    @return: The new head of reversed linked list.
    """
    def reverse(self, head):
        # write your code here
        if(head==None):return None
        dummy=None
        while(True):
            pre=head.next
            head.next=dummy
            dummy = head
            head=pre
            if(head==None):break
        return dummy




node1=ListNode(1)
node2=ListNode(2)
node1.next=node2
s=Solution()
result=s.reverse(node1)
while(result!=None):
    print(result.val)
    result=result.next

猜你喜欢

转载自blog.csdn.net/wenqiwenqi123/article/details/80624929
今日推荐