[LeetCode] Partition List 分割单链表

给你一个单链表和一个整数x,调整单链表的元素的位置,使得前半部分的值小于x,后半部分的值大于x。

下面的算法的思路和单链表快速排序的思路是一样的,该算法有可能改变节点的相对顺序。

ListNode *partition(ListNode *head, int x) {

        ListNode* slow = head;
        ListNode* fast = head;

        while(fast)
        {
                if(fast->val < x) // note the less-than-equal operator here
                // Input: 5->4->3 and x = 4
                // Output: 4->3->5
                {
                        swap(slow->val, fast->val);
                        slow = slow->next;
                }

                fast = fast->next;
        }
 
        return head;
}

2. 下面的算法可以保持相对顺序不变。

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.

思路很简单:先找出链表的长度和链表的尾节点,然后遍历链表,如果当前节点的值小于target,跳到下一个节点,如果当前节点的值大于等于target,则把这个节点移动到链表的末端。

/**
 * 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 *p= new ListNode(0);
        p->next = head;
        head = p; // used to save the result head.
        ListNode *last=head; // used to get the last node
         
        if (head->next==NULL){return head->next;}
         
        int n=0; //length of the list
        while (last->next!=NULL){ last=last->next; n++; } //get the length and last node
         
        while (n>0){  // in case  of non-stop loop, count n.
            if (p->next->val < x){  // val<x keep the node
                p=p->next;
                n--;
            }else{                  // val>=x move to last
                last->next = new ListNode(p->next->val);    // add node to the last
                last = last->next;
                p->next = p->next->next;                    //delete current node
                n--;
            }
        }
        return head->next;  //the 1st node is elmininated 
    }
};


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值