Partition List

来源:互联网 发布:网络零售的特点与模式 编辑:程序博客网 时间:2024/05/02 01:52
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的串和大于等于x的串。设置4个指针,分别表示这两个串的头尾。注意头指针要用新节点new ListNode(0)而不能用head,否则在第一轮就会把head后的数据丢掉。完成子串的分配后,我们只要把子串头尾相连即可,最后释放掉新建的节点。代码如下:

/** * 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 *s1=new ListNode(0),*s2=s1,*b1=new ListNode(0),*b2=b1,*tmp=head;        while(tmp!=NULL){            if(tmp->val<x){                s2->next=tmp;                tmp=tmp->next;                s2=s2->next;                s2->next=NULL;            }            else{                b2->next=tmp;                tmp=tmp->next;                b2=b2->next;                b2->next=NULL;            }        }        s2->next=b1->next;        head=s1->next;        free(s1);        free(b1);        return head;    }};
0 0
原创粉丝点击