[Cattle] list split off net practice

Links:
Original title Source
Source: Cattle-off network

[Programming questions] list split
heat index: 43019 Time limit: 3 seconds to space constraints: 32768K
algorithm knowledge to explain the video

Write code, a given value of x is divided into two parts, reference will list all less than x nodes ahead of nodes greater than or equal to x

Given a list head pointer ListNode * pHead, return to the head pointer list rearranged. Note: Keep the original data sequence unchanged after the split.

Ideas:

One can see the results of this question I thought of the idea to create two lists, a list put all nodes less than the specified x, and the other in equal amplification, and finally combined the two lists do not is to ask

note:

(1) Mark the first two lists of nodes, the need to use when splicing
(2) Consider an empty exception

Unrealized idea:
Since this can get two lists, then why not (you can create a list) it?

X is smaller than the section of the chain into the nod, greater than or equal to the tail into the linked list is not the final answer to form it.

Code

I realize that (the place can be optimized: the tail interpolation algorithm to extract out as a method) of two lists:

   public ListNode partition(ListNode pHead, int x) {
        // write code here
        ListNode left = null;
        ListNode right = null;
        ListNode p1 = null;
        ListNode p2 = null;
        while(pHead!=null){
            if(pHead.val<x){
                if(left == null){
                    left = new ListNode(pHead.val);
                    p1 = left; //左链表的头节点
                }else{
                    left.next = new ListNode(pHead.val);
                    left = left.next;
                }
            }else{
                if(right == null){
                    right = new ListNode(pHead.val);
                    p2 = right;    //右链表的头节点
                }else{
                    right.next = new ListNode(pHead.val);
                    right = right.next;
                }
            }
            pHead = pHead.next;
        }

        if(p1==null){
            return p2;
        }
        if(p2==null){
            return p1;
        }
        //走到这里说明都不为空,需要连接
        //找到左链表的最后一个节点将其与右链表连接
        ListNode cur = p1;
        while(cur.next!=null){
            cur = cur.next;
        }
        cur.next = p2;
        return p1;
    }

Wang also pointed out that if there is an error!

Published 57 original articles · won praise 11 · views 10000 +

Guess you like

Origin blog.csdn.net/qq_42419462/article/details/103303540