Partition List

来源:互联网 发布:itunes更新软件 编辑:程序博客网 时间:2024/04/29 06:14

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

 

0 0
原创粉丝点击