转载

LeetCode分隔链表

LeetCode分隔链表

题目链接地址

  • 解题思路

    用双链表法

    链表一: 1->2->2

    链表二:4->3->5

  • python代码

    
    # Definition for singly-linked list.
    
    
    # class ListNode(object):
    
    
    # def __init__(self, x):
    
    
    # self.val = x
    
    
    # self.next = None
    
    
    class Solution(object):
      def partition(self, head, x):
          """ :type head: ListNode :type x: int :rtype: ListNode """
          startOne, startTwo = None, None
          endOne, endTwo = None, None
    
          temp = head
    
          while temp != None:
              if temp.val < x:
                  if endOne == None:
                      startOne = temp
                      endOne = temp
                  else:
                      endOne.next = temp
                      endOne = temp
    
              else:
                  if endTwo == None:
                      startTwo = temp
                      endTwo = temp
                  else:
                      endTwo.next = temp
                      endTwo = temp
    
              temp = temp.next
    
          if endTwo != None:
              endTwo.next = None
    
          #防止链表一为空
          if endOne != None:
              endOne.next = startTwo
              return startOne
          else:
              return startTwo
正文到此结束
本文目录