zoukankan      html  css  js  c++  java
  • LeetCode OJ--Partition List

    http://oj.leetcode.com/problems/partition-list/

    链表的处理

    #include <iostream>
    using namespace std;
     
    struct ListNode {
         int val;
         ListNode *next;
         ListNode(int x) : val(x), next(NULL) {}
     };
     
    class Solution {
    public:
        ListNode *partition(ListNode *head, int x) {
            ListNode *head1 = NULL,*head2 = NULL,*tail1 = NULL,*tail2 = NULL,*p = NULL;
            p = head;
            bool flag1 = 0,flag2 = 0;
            while(p)
            {
                if(p->val<x)
                {
                    if(flag1 == 0)
                    {
                        head1 = tail1 = p;
                        flag1 = 1;
                    }
                    else
                    {
                        tail1->next = p;
                        tail1 = p;
                    }
                }
                else
                {
                    if(flag2 == 0)
                    {
                        head2 = tail2 = p;
                        flag2 = 1;
                    }
                    else
                    {
                        tail2->next = p;
                        tail2 = p;
                    }
                }
                p = p->next;
            }
            if(head1 == tail1 && tail1 == NULL)
                return head2;
            tail1->next = head2;
            if(tail2)
            tail2->next = NULL;
            return head1;
    
        }
    };
    
    int main()
    {
        ListNode *n1 = new ListNode(1);
        ListNode *n2 = new ListNode(4);
        ListNode *n3 = new ListNode(3);
        ListNode *n4 = new ListNode(2);
        ListNode *n5 = new ListNode(5);
        ListNode *n6 = new ListNode(2);
        n1->next = n2;
        n2->next = n3;
        n3->next = n4;
        n4->next = n5;
        n5->next = n6;
        ListNode *ans;
        Solution myS;
        ans = myS.partition(NULL,6);
        return 0;
    }
  • 相关阅读:
    实心菱形
    进制转换
    简单题目
    一元二次方程求解
    反转整数
    最大公约数
    数老鼠
    “鱼额宝”
    数组第K小数
    最大子数组和
  • 原文地址:https://www.cnblogs.com/qingcheng/p/3548748.html
Copyright © 2011-2022 走看看