面试中常见链表问题6:划分链表

来源:互联网 发布:centos输入法下载安装 编辑:程序博客网 时间:2024/06/05 15:24
    给定单链表和一个k值,把小于k值节点排在大于等于k值节点之前。比如说1->4->3->2->5->2和 x = 3,则返回1->2->2->4->3->5。
ListNode* partition(ListNode* head, int x) {if(head == NULL || head->next == NULL)return head;ListNode *pHeadA = new ListNode(0);ListNode *pHeadB = new ListNode(0);ListNode *p1 = pHeadA;ListNode *p2 = pHeadB;while(head != NULL){ListNode *tmp = head;head = head->next;tmp->next = NULL;if(tmp->val < x){p1->next = tmp;p1 = tmp;}else{p2->next = tmp;p2 = tmp;}}p1->next = pHeadB->next;return pHeadA->next;}
0 0