码迷,mamicode.com
首页 > 其他好文 > 详细

86. Partition List

时间:2018-09-25 12:41:11      阅读:100      评论:0      收藏:0      [点我收藏+]

标签:else   partition   ==   思路   art   整数   col   图片   png   

一、题目

  1、审题

技术分享图片

  2、分析

    给出一个整数链表,和一个目标数 x,将链表中节点值 < x 的节点放在值为 x 节点的左边,且保持链表原来的节点顺序。

 

二、解答

  1、思路:

    方法一、

      新建两个伪头结点,head1、head2,遍历链表节点:

      ①、若 val < x,则在 head1 后添加该节点

      ②、否则在 head2 后添加该节点

      ③、将head1 与 head2拼接,同时去除两个伪头结点。

public ListNode partition2(ListNode head, int x) {

        if(head == null || head.next == null)
            return head;
        
        ListNode fakeHead = new ListNode(0);
        fakeHead.next = head;
        ListNode pre = fakeHead;
        ListNode cur = head;
        ListNode next = new ListNode(x);
        ListNode head2 = next;
        
        while(cur != null) {
            if(cur.val < x) {
                pre.next = cur;
                pre = pre.next;
            }
            else {//if(cur.val >= x) {
                next.next = cur;
                next = next.next;
            }
            cur = cur.next;
        }
        next.next = null;
        pre.next = head2.next;
        return fakeHead.next;
    }

 

86. Partition List

标签:else   partition   ==   思路   art   整数   col   图片   png   

原文地址:https://www.cnblogs.com/skillking/p/9698756.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!