LeetCode—86 分隔链表 Cpp&Python
题目要求:给定一个链表和一个特定值 x,对链表进行分隔,使得所有小于 x 的节点都在大于或等于 x 的节点之前。
过程如下:
输入: head = 1->4->3->2->5->2, x = 3
输出: 1->2->2->4->3->5
一、方法与思路
通过创建两个虚拟的头节点less_head和more_head,同时创建两个节点less_ptr和more_ptr分别指向前者。对传入链表进行遍历,通过less_ptr和more_ptr使小于x值的节点插入less_head虚拟头节点,大于x值的节点插入到more_head的虚拟头节点,并使得其位置位于相对应链表尾部。最后连接less_head和more_head并返回合适位置。
过程大致如下:
二、C++代码
#include <stdio.h>
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
ListNode* partition(ListNode* head, int x) {
ListNode less_head(0);
ListNode more_head(0);
ListNode *less_ptr = &less_head;
ListNode *more_ptr = &more_head;
while(head){
if (head->val < x){
less_ptr->next = head;
less_ptr = head;
}
else {
more_ptr->next = head;
more_ptr = head;
}
head = head->next;
}
less_ptr->next = more_head.next;
more_ptr->next = NULL;
return less_head.next;
}
};
int main(){
ListNode a(1);//测试用例
ListNode b(4);
ListNode c(3);
ListNode d(2);
ListNode e(5);
ListNode f(2);
a.next = &b;
b.next = &c;
c.next = &d;
d.next = &e;
e.next = &f;
Solution solve;
ListNode *head = solve.partition(&a, 3);
while(head){
printf("%d\n", head->val);
head = head->next;
}
return 0;
}
三、python代码
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def partition(self, head: ListNode, x: int) -> ListNode:
less = ListNode(0)
more = ListNode(0)
p1 = less
p2 = more
while head:
if head.val < x:
p1.next = head
p1 = p1.next
else:
p2.next = head
p2 = p2.next
head = head.next
p1.next = more.next
p2.next = None
return less.next