leetcode: Partition List

来源:互联网 发布:python 记录访客数据 编辑:程序博客网 时间:2024/05/20 15:39


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.


非常机智的实现,因为需要是稳定的,所以保持相对位置不变,设置两个dummy头结点分别维护val小于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 head;        ListNode dummy_less(INT_MIN);//设置两个dummy节点方便实现        ListNode dummy_greater(INT_MIN);        auto less_cur = &dummy_less;//指向两个dummy节点的指针        auto greater_cur = &dummy_greater;        for( ListNode *cur = head; cur; cur = cur->next){            if( cur->val < x){                less_cur->next = cur;                less_cur = less_cur->next;            }            else{                greater_cur->next = cur;                greater_cur = greater_cur->next;            }        }        less_cur->next = dummy_greater.next;//链接两个链表        greater_cur->next = NULL;        return dummy_less.next;    }};


0 0