自己做出来的,还可以
分析: 本来想先找到第一个小的点和第一个大的点,但是谁大谁小也不知道。 比较复杂,所以想到在最开始加新的点
1. list 是否为空
2. 构建small 和 big node. 用tra 遍历链表
if tra.val<x , -> small 列表
else -> big 列表
在small里, 还用注意因为题目要求small在前(特殊顺序,不是对称的), 所以要处理最后一个点的情况
3. 综合来看
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# @param head, a ListNode
# @param x, an integer
# @return a ListNode
def partition(self, head, x):
if head==None:
return head
small,big = ListNode(0),ListNode(0)
smallhead,bighead = small,big
tra = head
while tra!=None:
if tra.val<x:
small.next = tra
small = small.next
if tra.next==None:
big.next = None
else:
big.next = tra
big = big.next
tra = tra.next
small.next = bighead.next
return smallhead.next
C++
/**
* 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==NULL){
return head;
}
ListNode *smallhead = new ListNode(0);
ListNode *bighead = new ListNode(0);
ListNode *small = smallhead;
ListNode *big = bighead;
ListNode *tra = head;
while (tra!=NULL){
if (tra->val<x){
small->next = tra;
small = small->next;
if (tra->next==NULL){
big->next = NULL;
}
}else{
big->next = tra;
big = big->next;
}
tra = tra->next;
}
small->next = bighead->next;
return smallhead->next;
}
};