• (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;
        }
    };
  • 相关阅读:
    对实时的视屏流进行处理
    opencv读取并播放avi视屏
    opencv中读取显示图像
    为什么既要有IP地址还要有MAC地址
    继承中构造、析构 与 拷贝构造、赋值中的调用区别
    拷贝构造函数和赋值符函数——转
    inline修饰虚函数的问题
    菱形继承产生的问题及解决
    迭代器模式
    备忘录模式
  • 原文地址:https://www.cnblogs.com/AndyJee/p/4464138.html
Copyright © 2020-2023  润新知