leetcode 83& 86
思路:两个指针,一个是当前指针cur,一个是当前指针的下一个nex。如果cur.val
等于nex.val,那么cur.next = nex.next,nex向后移动为nex.next,当前指针cur不变,继续循环;如果cur.val不等于nex.val,那么cur和nex都向后移动一位,继续循环。

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def deleteDuplicates(self, head: 'ListNode') -> 'ListNode':
        if head == None:
            return head
        cur = head
        nex = cur.next
        while nex:
            if cur.val == nex.val:
                cur.next = nex.next
                nex = nex.next
 
   
            else:
                cur = nex
                nex = nex.next
        return head 
                

leetcode 83& 86
思路:重新创建两个聊表,其中一个存储小于x的数,另一个存储大于x的数。创建链表的过程中,小于x的链表当前指针用less_point表示,大于x的链表当前指针用more_point表示。

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def partition(self, head: 'ListNode', x: 'int') -> 'ListNode':
        smaller_dummy = ListNode(-1)
        less_point = smaller_dummy
        
        bigger_dummy = ListNode(-1)
        more_point = bigger_dummy
        
        cur = head
        
        while cur:
            if cur.val < x: 
                less_point.next = cur
                less_point = cur
                
            else:
                more_point.next = cur
                more_point = cur
            
            cur = cur.next
        
        less_point.next = bigger_dummy.next
        more_point.next = None
        return smaller_dummy.next

相关文章:

  • 2022-02-16
  • 2021-07-29
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-04-04
  • 2021-09-21
猜你喜欢
  • 2021-08-19
  • 2021-10-25
  • 2021-11-02
  • 2021-11-22
  • 2021-10-11
  • 2021-09-09
  • 2021-06-25
相关资源
相似解决方案