Description
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.
Example:
Input:
head = 1->4->3->2->5->2, x = 3
Output:
1->2->2->4->3->5
分析
题目的意思是:给定一个链表,一个数x,要求比x小的放在链表前面,大于等于x的放在链表后面。
- 只需要遍历一遍就行了,slow指针指向要插向的位置,fast来寻找需要移动的结点。
代码
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* partition(ListNode* head, int x) {
if(!head) return head;
ListNode* dummy=new ListNode(0);
ListNode* slow=dummy;
ListNode* fast=dummy;
dummy->next=head;
while(fast&&fast->next){
if(fast->next->val>=x){
fast=fast->next;
}else{
if(fast==slow){
fast=fast->next;
slow=slow->next;
}else{
ListNode* temp=fast->next;
fast->next=temp->next;
temp->next=slow->next;
slow->next=temp;
slow=slow->next;
}
}
}
return dummy->next;
}
};
Python实现
思路很直接,构建了2个链表,l1则是拼接的小于x的节点,l2则是拼接的大于等于x的节点,然后这里注意遍历的时候,cur为了避免形成环,需要把它设置为None,然后再跳转到下一个节点。
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def partition(self, head: Optional[ListNode], x: int) -> Optional[ListNode]:
# two pointer
l1 = ListNode(-1)
l2 = ListNode(-1)
p2 = l2
p1 = l1
cur = head
while cur:
next_node = cur.next
if cur.val<x:
p1.next = cur
p1 = p1.next
else:
p2.next = cur
p2 = p2.next
cur.next = None
cur = next_node
p1.next = l2.next
return l1.next