LeetCode-- Partition List

来源:互联网 发布:网络歌曲偷菜歌 编辑:程序博客网 时间:2024/06/08 00:48

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.

思路:刚学完数组的快速排序算法,就遇到了这个链表的partition问题,不过我感觉貌似比数组的简单。首先遍历链表,找到比基准元素大的第一个数,然后从这里开始,比基准元素大的数不管,比基准元素小的数用尾插法插入到pre的后面,画图容易理解。

/** * 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) {        ListNode* dummy=new ListNode(-1);        dummy->next=head;        ListNode* pre=dummy,*cur=head;        while(pre->next&&pre->next->val<x)            pre=pre->next;        cur=pre;        while(cur->next){            if(cur->next->val<x){                ListNode* tmp=cur->next;                cur->next=tmp->next;                tmp->next=pre->next;                pre->next=tmp;                pre=pre->next;            }            else{                cur=cur->next;            }        }        return dummy->next;    }};