leetcode题目例题解析(十)

leetcode题目例题解析(十)

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) {
        ListNode h(0);
        h.next = head;
        ListNode *big = head;
        ListNode * small = NULL;
        ListNode* temp = NULL, *before;
        before = &h;
        while(big) {
            if (big->val < x) {
                before->next = before->next->next;
                big->next = NULL;
                if (small == NULL) {
                    small = big;
                    temp = small;
                } else {
                    temp->next = big;
                    temp = temp->next;
                }
                big = before->next;
            } else {
                before = before->next;
                big = big->next;
            }
        }
        //对于一种全部比给定数大的情况,这是不用分组,这样就不需要使用到temp变量,temp就是NULL
        if (temp)
            temp->next = h.next;
        else 
            small = h.next;
        return small;
    }
};

原题目链接:
https://leetcode.com/problems/partition-list/description/

猜你喜欢

转载自blog.csdn.net/OzhangsenO/article/details/78680158
今日推荐