划分链表[java]

划分链表

http://www.nowcoder.com/questionTerminal/1dc1036be38f45f19000e48abe00b12f

import java.util.*;

/*
 * public class ListNode {
 *   int val;
 *   ListNode next = null;
 * }
 */

public class Solution {
    /**
     * 
     * @param head ListNode类 
     * @param x int整型 
     * @return ListNode类
     */
    public ListNode partition (ListNode head, int x) {
        // write code here
        if (head == null) return head;
        ListNode h1 = new ListNode(0);
        ListNode h2 = new ListNode(0);
        ListNode n1 = h1;
        ListNode n2 = h2;
        ListNode tmp = head;
        while (tmp != null) {
            if (tmp.val < x) {
                n1.next = tmp;
                n1 = tmp;
            } else {
                n2.next = tmp;
                n2 = tmp;
            }
            tmp = tmp.next;
        }
        n2.next = null;
        n1.next = h2.next;
        return h1.next;
    }
}
全部评论

相关推荐

07-28 16:37
门头沟学院 Java
哎,继续加油吧
ResourceUt...:能接到面试就已经是✌🏻了
腾讯一面2195人在聊
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
07-25 17:26
点赞 评论 收藏
分享
评论
3
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务