[Cattle] list split off network

One, Title Description

Write code, a given value of x is divided into two parts, reference will list all less than x nodes ahead of node x equal to or greater than a given a list head pointer ListNode * pHead, after the return to rearrange head pointer list. Note: keep the original data sequence unchanged after the split.

Second, the problem-solving ideas:

1, first determines whether the list is empty or only one element.
2, create two lists big and small, if the current node list element into small smaller than x; if the current node element ratio x is inserted into the large big list.
3, the two chain end to end.

Third, Code Description:

import java.util.*;
/*
public class ListNode {
    int val;
    ListNode next = null;

    ListNode(int val) {
        this.val = val;
    }
}*/
public class Partition {
    public ListNode partition(ListNode pHead, int x) {
       //链表为空
       if(pHead==null){
           return null;
       }
       //链表只有一个元素
        if(pHead.next==null){
            return pHead;
        }
        ListNode smallHead=new ListNode(-1);
        ListNode smallTail=smallHead;
        ListNode bigHead=new ListNode(-1);
        ListNode bigTail=bigHead;
        //遍历链表,比较cur的val和x的大小关系
        for(ListNode cur=pHead;cur!=null;cur=cur.next){
        //当前值小于基准值,插入到 smallTail后面, 创建崭新的节点(新节点的next一定是 null)
            if(cur.val<x){
                smallTail.next=new ListNode(cur.val);
                smallTail=smallTail.next;
            }
            //当前值小于基准值
            else{
                bigTail.next=new ListNode(cur.val);
                bigTail=bigTail.next;
            }
        }
        //将两个链表的首尾相接
        smallTail.next=bigHead.next;
        return smallHead.next;
    }
}
Published 75 original articles · won praise 14 · views 1900

Guess you like

Origin blog.csdn.net/qq_45328505/article/details/104582880