leetcode笔记--Partition List

来源:互联网 发布:app软件测试工程师 编辑:程序博客网 时间:2024/05/29 17:18

题目:难度(Medium)

Given a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x.
You should preserve the original relative order of the nodes in each of the two partitions.
For example,
    Given 1->4->3->2->5->2 and x = 3,
    return 1->2->2->4->3->5.
Tags:Linked List Two Pointers

分析:将链表中<x的元素都放到链表的前面部分,<x的部分里和>=x的部分里各个元素的相对位置不变。可以遍历整个链表,将元素值>=x的节点摘下来组成一个新的链表,然后将旧链表的剩余部分与摘下来的新链表相链接。值得注意的是,当用head2记录摘下的新链表的头节点时,设r指向head2链表的尾节点位置,由于head2中的节点都是从head中摘取得到的,所以一定要注意每次使得head2的尾节点r.next=None,否则会产生环路。

例如:设单链表为1->3->2->null,输入的x=3,则按照我的算法思路得到的最后的链表应该如下(算法中不讲r.next = None):


那么此时形成的链表就为是1->2->3->2->3->2->3...形成一个环路,所以,一定要记得使得head2的尾节点r.next总是为None

代码实现:

# Definition for singly-linked list.# class ListNode(object):#     def __init__(self, x):#         self.val = x#         self.next = Noneclass Solution(object):    def partition(self, head, x):        """        :type head: ListNode        :type x: int        :rtype: ListNode        """        if head is None:            return head        #将链表拆成2个链表再链接起来        #将元素值>=x的节点摘下来组成一个新的链表,最后将原来的剩余的链表与摘下的新链表连接起来        p = head        head2 = None        #head2记录摘下来的链表的头节点,head为<x的值的链表的头节点        #如果头节点的值就比x大于或等于,直接摘下头节点,处理特殊的头节点的情况        while head is not None and head.val >= x:            if head2 is None:                head2 = head                #head2.next = None                r = head2            else:                r.next = head                r = head            head = head.next            p = head            #r指向摘得的链表的尾节点,注意使r.next = None 否则容易产生环路            r.next = None                        #处理不是头节点满足>=x的其他节点        if p is not None:            q = p.next            while q is not None:                if q.val >= x:                    p.next = q.next                    if head2 is None:                        head2 = q                        r = head2                        #r总是记录摘得的链表的尾节点                    else:                        r.next = q                        r = q                    q = q.next                    #r指向摘得的链表的尾节点,注意使r.next = None 否则容易产生环路                    r.next = None                else:                    p = q                    q = q.next                            #此时p指向原链表剩余部分的最后一个节点位置            p.next = head2            return head        else:            #p is None说明从头节点开始,所有节点均满足>=x,此时直接返回head2            return head2


0 0
原创粉丝点击