zoukankan      html  css  js  c++  java
  • 86. Partition List

    该题题意为让小于指定值的节点位于链表前面,大于等于指定值的节点在链表后面,且保留原有顺序。

    在这里我们首先为链表增加一个伪链表头prehead,这个链表头的next指向head。

    定义三个指针,

    1)插入指针insertnode为空

    2)遍历指针cur指向head

    3)指向遍历指针前面节点的指针prenode,此时prenode应该指向prehead。

    然后当当前指针cur不为空的时候对链表进行循环遍历

    1)当cur的值大于等于指定值的时候且插入指针还是空的时候,将插入指针指向prenode。

    2)如果cur的值小于指定值且插入指针不为空的时候,将当前节点插入到插入节点后面,并让插入指针指向插入到新插入的节点,prenode以及cur继续指向下一个节点。

    代码如下:

     1 /**
     2  * Definition for singly-linked list.
     3  * public class ListNode {
     4  *     int val;
     5  *     ListNode next;
     6  *     ListNode(int x) { val = x; }
     7  * }
     8  */
     9 class Solution {
    10     public ListNode partition(ListNode head, int x) {
    11         ListNode prehead = new ListNode(0);
    12         prehead.next = head;
    13         ListNode cur = head;
    14         ListNode insertnode = null;
    15         ListNode prenode = prehead;
    16         
    17         while(cur != null){
    18             if( cur.val >= x && insertnode == null ){
    19                 insertnode = prenode; 
    20             }
    21             
    22             if( cur.val < x && insertnode != null){
    23                 prenode.next = cur.next;
    24                 cur.next = insertnode.next;
    25                 insertnode.next = cur;
    26                 insertnode = insertnode.next;
    27                 cur = prenode.next;
    28                 continue;
    29             }
    30             
    31             prenode = prenode.next;
    32             cur = cur.next;
    33             
    34         }
    35         
    36         return prehead.next;
    37     }
    38 }

    END

  • 相关阅读:
    工作总结(二):Web Design
    工作总结(一):Linux C
    三十分钟学会AWK
    MySQL并发复制系列二:多线程复制 2016
    修改MySQL 5.7.9版本的root密码方法以及一些新变化整理
    sync_binlog innodb_flush_log_at_trx_commit 浅析
    MariaDB的"response time"插件
    Python学习九:列表生成式
    python中的深拷贝和浅拷贝理解
    Mycat 配置
  • 原文地址:https://www.cnblogs.com/sssysukww/p/8892911.html
Copyright © 2011-2022 走看看