双指针+双哑节点划分链表

划分链表

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
        ListNode dummy = new ListNode(-1);
        ListNode dummy2 = new ListNode(-1);


        ListNode p = dummy;
        ListNode q = dummy2;

        ListNode temp = head;

        while(temp != null){
            if(temp.val < x){
                p.next = temp;
                p = temp;
            }else{
                q.next = temp;
                q = temp;
            }
            temp = temp.next;
        }
        p.next = dummy2.next;
        q.next = null;
        return dummy.next;


 }
}
全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务