zoukankan      html  css  js  c++  java
  • LeetCode 86 ——分隔链表

    1. 题目

    2. 解答

    从前向后遍历链表,将结点值小于 x 的结点放入到新链表 1 中,将结点值大于等于 x 的结点放入新链表 2 中。最后,将新链表 2 拼接在新链表 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) {
            
            if (head == NULL || head->next == NULL) return head;
            
            ListNode *new_head1 = new ListNode(0); // 新建哨兵结点方便操作
            ListNode *temp1 = new_head1;
            
            ListNode *new_head2 = new ListNode(0); // 新建哨兵结点方便操作
            ListNode *temp2 = new_head2;
            
            while (head)
            {
                if (head->val < x) // 小于 x 的结点放入新链表 1
                {
                    temp1->next = head;
                    temp1 = head;
                }
                else // 大于等于 x 的结点放入新链表 2
                {
                    temp2->next = head;
                    temp2 = head;
                }
                
                head = head->next;
            }
            
            temp1->next = new_head2->next;
            temp2->next = NULL;
            
            return new_head1->next;   
        }
    };
    

    获取更多精彩,请关注「seniusen」!

  • 相关阅读:
    JSON格式化
    mysql字符串操作
    MySLQ排序后标记排行
    RestTemplate调用POST接口
    FULLTEXT INDEX全文索引
    Convert AS400 Spool to PFD Tools – PDFing
    openssl制作双向认证经过验证可行
    https web service in Tibco & PC
    Python获取百度浏览记录
    Python2.7学习
  • 原文地址:https://www.cnblogs.com/seniusen/p/9958568.html
Copyright © 2011-2022 走看看