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
.
Subscribe to see which companies asked this question
解答:
这道题可以这么来思考,找到第一个大于或等于x的节点,然后以此为分界线将链表分为前后两个链表,再将后一个链表中的所有小于x的节点依次加入前一个链表的尾部,最后再将后一个链表接到前一个链表的尾部。不过如果原链表的首节点就已经大于或等于x了,那么就直接将原链表中小于x的节点依次加入一个新链表中,再将原链表接到新链表的尾部,相当于是前一个链表开始为空而后一个链表开始就是整个原链表。当然这里要注意所有节点都大于或等于x的情况和所有节点都小于x的情况,还有空链表的情况,这些都可以通过控制局部变量的初值和一些条件判断语句来达到。
/** * Definition for singly-linked list. * struct ListNode { * int val; * struct ListNode *next; * }; */ struct ListNode* partition(struct ListNode* head, int x) { struct ListNode *pNode = head, *partition = NULL, *tmp, *tail; if(NULL == head){ return head; } if(head->val < x){ while(NULL != pNode){ if(NULL != pNode->next&&pNode->next->val >= x){ partition = pNode->next; tail = pNode; pNode = pNode->next; break; } else{ pNode = pNode->next; } } while(NULL != pNode){ if(NULL != pNode->next&&pNode->next->val < x){ tmp = pNode->next; pNode->next = pNode->next->next; tail->next = tmp; tail = tmp; } else{ pNode = pNode->next; } } tail->next = partition; } else{ partition = head; head = NULL; while(NULL != pNode){ if(NULL != pNode->next&&pNode->next->val < x){ tmp = pNode->next; pNode->next = pNode->next->next; if(NULL == head){ head = tmp; } else{ tail->next = tmp; } tail = tmp; } else{ pNode = pNode->next; } } if(NULL != head){ tail->next = partition; } else{ head = partition; } } return head; }