• 46. Partition List


    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 的结点。

    注意:记住两个表尾,中间不能将其 next 指针设置为空。最后将存小值的表尾链接在另一个前面,两一个表尾 next 置为 NULL.

    /**
     * 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 *head1, *head2, *tail1, *tail2;
            head1 = head2 = tail1 = tail2 = NULL;
            while(head) {
                if(head->val >= x) {
                    if(head2 == NULL) head2 = tail2 = head;
                    else { tail2->next = head; tail2 = tail2->next; }
                } else {
                    if(head1 == NULL) head1 = tail1 = head;
                    else { tail1->next = head; tail1 = tail1->next; }
                }
                head = head->next;
            }
            if(head2) tail2->next = NULL;
            if(head1) tail1->next = head2;
            else head1 = head2;
            return head1;
        }
    };
    
  • 相关阅读:
    项目总结
    css的div垂直居中的方法,百分比div垂直居中
    HTTP 协议
    web和网络基础
    设计模式--策略模式
    设计模式--单例模式
    mockjs的基本使用入门
    浏览器标签页切换时jquery动画的问题
    javascript中的vavigator对象
    编写可维护的JavaScript-随笔(七)
  • 原文地址:https://www.cnblogs.com/liyangguang1988/p/3953999.html
Copyright © 2020-2023  润新知