鏈接https://www.nowcoder.com/questionTerminal/0e27e0b064de4eacac178676ef9c9d70
來源:牛客網
編寫代碼,以給定值x爲基準將鏈表分割成兩部分,所有小於x的結點排在大於或等於x的結點之前 給定一個鏈表的頭指針 ListNode* pHead,請返回重新排列後的鏈表的頭指針。注意:分割以後保持原來的數據順序不變。
代碼:
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};*/
class Partition {
public:
ListNode* partition(ListNode* pHead, int x) {
ListNode* cur = pHead;
ListNode* lessHead,*lessTail,*greaterHead,*greaterTail;
lessHead = lessTail = (ListNode*)malloc(sizeof(ListNode));
greaterHead = greaterTail = (ListNode*)malloc(sizeof(ListNode));
lessTail -> next = NULL;
greaterTail -> next = NULL;
while(cur != NULL)
{
if(cur->val < x)
{
lessTail -> next = cur;
lessTail = cur;
}
else
{
greaterTail -> next = cur;
greaterTail = cur;
}
cur = cur ->next;
}
lessTail -> next = greaterHead -> next;
greaterTail ->next = NULL;
ListNode* list = lessHead ->next;
free(lessHead);
free(greaterHead);
return list;
}
};