Partition List

来源:互联网 发布:qq2012国际版 linux 编辑:程序博客网 时间:2024/06/08 17:09

问题: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.

思路:遍历一遍。将这一个链表拆成两条链表,一个里面全是小于x的,另一个里面是大于等于x的。新链表都在尾部插入新结点,可以保证相对顺序不变。注意特殊情况:可能整个原链表中的结点都是小于(或者大于)x的。

代码一:

/** * 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)            return NULL;        ListNode *big_head = NULL, *small_head = NULL;        ListNode *big_end, *small_end;                while(head != NULL)        {            if(head->val >= x)                add_big_list(big_head, big_end, head);            else                add_small_list(small_head, small_end, head);            head = head->next;        }        if(big_head != NULL && small_head != NULL)        {            small_end->next = big_head;            big_end->next = NULL;            return small_head;        }        if(big_head == NULL)        {            small_end->next = NULL;            return small_head;        }        else        {            big_end->next = NULL;            return big_head;        }    }        void add_big_list(ListNode* &head, ListNode* &end, ListNode *p)    {        if(head == NULL)        {            head = p;            end = p;            return;        }        end->next = p;        end = p;    }        void add_small_list(ListNode* &head, ListNode* &end, ListNode *p)    {        if(head == NULL)        {            head = p;            end = p;            return;        }        end->next = p;        end = p;    }};

代码二:优化。一、为两个新链表建立空头结点来使操作保持一致。二、不创建函数了,直接在对原始链表的遍历循环中做插入操作。

class Solution {public:    ListNode *partition(ListNode *head, int x) {        ListNode small_head(0);        ListNode big_head(0);                ListNode *p1 = &small_head;        ListNode *p2 = &big_head;                while(head != NULL)        {            if(head->val < x)            {                p1->next = head;                p1 = p1->next;            }            else            {                p2->next = head;                p2 = p2->next;            }            head = head->next;        }        p1->next = big_head.next;        p2->next = NULL;        return small_head.next;    }};

0 0