2023年7月7日 星期五

[86] Partition List

啊......不知道說什麼好.....
就這樣好了 XD 

給一個linked list 和一個數字X , 要把linked list 排成 :
比X小的在左邊,比X大的在右邊,它們的相對位置要依照沒有排以前的一樣
雖然還是覺得 linked list 算是我的強項(吧)(真敢說)
但是為什麼寫起來都這麼醜呢?(所以說根本就不強吧哈哈哈XD!)


/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* partition(struct ListNode* head, int x){
struct ListNode *p1 , *p2, *p2Head, *pRun;
pRun=head;
p1=p2=p2Head=NULL;
if (head==NULL || head->next==NULL)
return head;
while (pRun !=NULL)
{
if (pRun->val >= x)
{
if (p2!=NULL)
{
p2->next=pRun;
p2=p2->next;
}
else
{
p2Head=pRun;
p2=pRun;
}
}
else
{
if (p1 != NULL)
{
p1->next=pRun;
p1=p1->next;
}
else
{
p1=pRun;
head=pRun;
}
}
pRun=pRun->next;
}

if (p1!=NULL)
p1->next = p2Head;
if (p2 !=NULL)
p2->next= NULL;

return head;

}

沒有留言:

張貼留言