python_LintCode(简单)

题35. 翻转链表
翻转一个链表
样例:给出一个链表1->2->3->null,这个翻转后的链表为3->2->1->null

"""
Definition of ListNode

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 is None:
            return
        if head.next is None:
            return head
        new=head
        pre=None
        while new:
            res=new
            tmp=new.next
            new.next=pre
            pre=new
            new=tmp
        return pre

题96. 链表划分
给定一个单链表和数值x,划分链表使得所有小于x的节点排在大于等于x的节点之前。
你应该保留两部分内链表节点原有的相对顺序。
样例:给定链表 1->4->3->2->5->2->null,并且 x=3
返回 1->2->2->4->3->5->null

def partition(self, head, x):
        # write your code here
        # 借助了两个链表,一个存放小于的数字,另一个存放不小于的数字
        if head is None:
            return head
        minl=ListNode(0)
        pre1=minl
        maxl=ListNode(0)
        pre2=maxl
        pre=head
        while pre:
            if pre.val<x:
                pre1.next=pre
                pre1=pre1.next
            else:
                pre2.next=pre
                pre2=pre2.next
            pre=pre.next
        pre2.next=None##注意
        pre1.next=maxl.next
        return minl.next
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值