题意描述:
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.
For example,
Given 1->4->3->2->5->2
and x = 3,
return 1->2->2->4->3->5
.
四个指针,分别指向小于x部分链表的头和尾,;指向大于等于x部分链表的头和尾。 空间复杂度:O(1)
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 || head->next==NULL) return head;
ListNode* h1=NULL,*t1=NULL;
ListNode* h2=NULL,*t2=NULL;
ListNode* current=head,*next=NULL;
while(current!=NULL)
{
next=current->next;
if(current->val<x)
{
if(h1==NULL)
{
h1=current;
t1=current;
}
else
{
t1->next=current;
t1=t1->next;
}
t1->next=NULL;
}
else
{
if(h2==NULL)
{
h2=current;
t2=current;
}
else
{
t2->next=current;
t2=t2->next;
}
t2->next=NULL;
}
current=next;
}
if(h1==NULL)return h2;
t1->next=h2;
return h1;
}
};
python代码:
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def partition(self, head, x):
"""
:type head: ListNode
:type x: int
:rtype: ListNode
"""
if head==None or head.next==None:
return head
h1,t1=None,None
h2,t2=None,None
currentNode,nextNode=head,None
while currentNode!=None:
nextNode=currentNode.next
if currentNode.val<x:
if h1==None:
h1=currentNode
t1=currentNode
else:
t1.next=currentNode
t1=t1.next
t1.next=None
else:
if h2==None:
h2=currentNode
t2=currentNode
else:
t2.next=currentNode
t2=t2.next
t2.next=None
currentNode=nextNode
if h1==None:
return h2
t1.next=h2
return h1
优化:可以使用dummyNode减少判断,使代码更加简洁!!
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 || head->next==NULL) return head;
ListNode* h1=new ListNode(0),*t1=h1;
ListNode* h2=new ListNode(0),*t2=h2;
ListNode* current=head;
while(current)
{
if(current->val<x)
{
t1->next=current;
current=current->next;
t1=t1->next;
t1->next=NULL;
}
else
{
t2->next=current;
t2=t2->next;
current=current->next;
t2->next=NULL;
}
}
t1->next=h2->next;
return h1->next;
}
};
python代码:
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def partition(self, head, x):
"""
:type head: ListNode
:type x: int
:rtype: ListNode
"""
if head==None or head.next==None:
return head
h1=ListNode(0)
t1=h1
h2=ListNode(0)
t2=h2
current=head
while current:
if current.val<x:
t1.next=current
current=current.next
t1=t1.next
t1.next=None
else:
t2.next=current
t2=t2.next
current=current.next
t2.next=None
t1.next=h2.next
return h1.next
(完)