(LeetCode 86)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.

题目要求:

给一个链表和一个数值x,将所有小于x的结点放在所有大于或等于x的结点的前面。

要求不改变原链表结点的相对顺序。

解题思路:

在数组partition中,一般是通过首尾两个指针来进行前后遍历以及交换;

而在链表中,不需要进行元素的交换,可以通过创建两个新的头结点指针,来分别指向小于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) {
        ListNode *left_head=NULL,*left_tail=NULL;
        ListNode *right_head=NULL,*right_tail=NULL;
        ListNode *p=head;
        
        while(p){
            if(p->val<x){
                if(left_tail){
                    left_tail->next=p;
                    left_tail=left_tail->next;
                }
                else
                    left_head=left_tail=p;
            }
            else{
                if(right_tail){
                    right_tail->next=p;
                    right_tail=right_tail->next;
                }
                else
                    right_head=right_tail=p;
            }
            p=p->next;
        }
        
        if(right_tail)
            right_tail->next=NULL;
        if(left_tail)
            left_tail->next=right_head;
            
        return left_head?left_head:right_head;
    }
};
原文地址:https://www.cnblogs.com/AndyJee/p/4464138.html