[leetcode]Partition List

来源:互联网 发布:mac网线转接头怎么联网 编辑:程序博客网 时间:2024/06/09 14:43

Partition List

 

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.

解题思路:找出第一个大于等于目标数的指针与其前一个指针,然后从第一个大于等于目标数指针的后一个开始一次处理,将小于的

元素插入到第一个大于等于目标数元素指针的前面,以此来保持元素在原数组中的相对顺序不变


/** * 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(NULL == head || NULL == head->next) return head;                ListNode *firstGEptr = NULL, *preGEptr = NULL;        ListNode *nhead = head, *ptr = head;                //找出首个大于等于目标数的指针        for(;ptr != NULL; ptr = ptr->next){            if(ptr->val >= x) break;            preGEptr = ptr;        }        if(NULL == ptr) return head;        firstGEptr = ptr;                ListNode *q = NULL;                while(ptr && ptr->next){            q = ptr->next;            if(q->val < x){                //                ptr->next = q->next;                if(preGEptr){                     //目标指针不为头批针,摘下当前指针插入到preGEptr与firstGEptr之间                    q->next = firstGEptr;                    preGEptr->next = q;                    preGEptr = q;                }else{                    q->next = firstGEptr; //如果目标数指针为头指针                    preGEptr = q;                    nhead = q;                }            }else{                ptr = ptr->next;            }        }                return nhead;    }};


0 0
原创粉丝点击