LeetCode 86. 分隔链表(Partition List)

版权声明:转载请说明出处!!! https://blog.csdn.net/u012585868/article/details/83548767

题目描述

给定一个链表和一个特定值 x,对链表进行分隔,使得所有小于 x 的节点都在大于或等于 x 的节点之前。
你应当保留两个分区中每个节点的初始相对位置。

示例:

输入: head = 1->4->3->2->5->2, x = 3
输出: 1->2->2->4->3->5

解题思路1

把所有小于给定值的节点都移到前面,大于该值的节点顺序不变,相当于一个局部排序的问题。首先找到第一个大于或等于给定值的节点,用题目中给的例子来说就是先找到4,然后再找小于3的值,每找到一个就将其取出置于4之前即可。
代码展示1中的pre指针用来定位第一个大于或等于给定值的节点的前一个节点,cur指针则用来定位给定值之后第一个小于给定值的节点的前一个节点,借助辅助指针tmp来进行链表节点的移动操作。

这种解法的链表变化顺序为:

1 -> 4 -> 3 -> 2 -> 5 -> 2 

1 -> 2 -> 4 -> 3 -> 5 -> 2 

1 -> 2 -> 2 -> 4 -> 3 -> 5

代码展示1

/**
 * 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 *beforehead=new ListNode(0);
        ListNode *beforehead=(ListNode*)malloc(sizeof(ListNode));//建立头节点,用上句被注释的也可,上句中的0是拿来开辟内存的,其他值也可以
        beforehead->next=head;
        ListNode *pre=beforehead;
        ListNode *cur=head;
        while(pre->next&&pre->next->val<x){
            pre=pre->next;
        }
        cur=pre;
        while(cur->next){
            if(cur->next->val<x){
                ListNode *tmp=cur->next;
                cur->next=tmp->next;
                tmp->next=pre->next;
                pre->next=tmp;
                pre=pre->next;
            }
            else{
                cur=cur->next;
            }
        }
        return beforehead->next;
    }
};

解题思路2

此题还有一种解法,就是将所有小于给定值的节点取出组成一个新的链表,此时原链表中剩余的节点的值都大于或等于给定值,只要将原链表直接接在新链表后即可。

此种解法链表变化顺序为:

1.Original: 1 -> 4 -> 3 -> 2 -> 5 -> 2 
       New:

2.Original: 4 -> 3 -> 2 -> 5 -> 2 
       New: 1

3.Original: 4 -> 3 -> 5 -> 2 
       New: 1 -> 2

4.Original: 4 -> 3 -> 5 
       New: 1 -> 2 -> 2
  
5.Original: 
       New: 1 -> 2 -> 2 -> 4 -> 3 -> 5 

代码展示2

/**
 * 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 *beforehead=new ListNode(0);
        ListNode *beforehead=(ListNode*)malloc(sizeof(ListNode));
        ListNode *newbeforehead=(ListNode*)malloc(sizeof(ListNode));
        beforehead->next=head;
        ListNode *cur=beforehead;
        ListNode *p=newbeforehead;
        while(cur->next){
            if(cur->next->val<x){
                p->next=cur->next;
                p=p->next;
                cur->next=cur->next->next;
                p->next=NULL;
            }
            else{
                cur=cur->next;
            }
        }
        p->next=beforehead->next;
        return newbeforehead->next; 
    }
};

猜你喜欢

转载自blog.csdn.net/u012585868/article/details/83548767
今日推荐