思路:两个指针,一个是当前指针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
思路:重新创建两个聊表,其中一个存储小于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