Leedcode11 Linked List Segmentation

public class ListNode {
    int val;
    ListNode next = null;

    ListNode(int val) {
        this.val = val;
    }
}

method one:

public class Partition1 {
    public ListNode partition(ListNode pHead,int x){
        //新建两个链表
        //一个用来存储小于x的结点,一个用来存储大于x的结点并保存头结点
        //最后让第一条链表的next=第二条链表的head
        ListNode preHead = new ListNode(0);
        ListNode curHead = new ListNode(0);
        ListNode prev = preHead;
        ListNode cur = curHead;
        while(pHead != null){
            if(pHead.val < x){
                preHead.next = pHead;
                preHead = preHead.next;
            }else{
                curHead.next = pHead;
                curHead = curHead.next;
            }
            pHead = pHead.next;
        }
        prev = prev.next;
        cur = cur.next;
        //连接两个链表
        preHead.next = cur;
        //cur不为空,让curHead的尾结点为空
        if(cur != null){
            curHead.next = null;
        }
        if(prev == null){
            return cur;
        }
        return prev;
    }
}

Method 2: Stack

import java.util.Stack;

//利用栈
public class Partition2 {
    public ListNode partition(ListNode pHead,int x){
        //创建一个栈,将所有小于x得值存放在栈中
        //将栈中元素一一取出,并采用头茬重新插入链表中
        if(pHead == null){
            return pHead;
        }
        Stack<Integer> stack = new Stack<>();
        //创建两个工具结点
        ListNode prev = null;
        ListNode cur = pHead;
        while(cur != null){
            if(cur.val < x){
                stack.add(cur.val);
                if(cur == pHead){
                    pHead = pHead.next;
                    cur = pHead;
                }else{
                    cur = cur.next;
                    prev.next = cur;
                }
            }else{
                prev = cur;
                cur = cur.next;
            }
        }
        while(!stack.isEmpty()){
            //头插
            ListNode newNode = new ListNode(stack.pop());
            newNode.next = pHead;
            pHead = newNode;
        }
        return pHead;
    }
}

Guess you like

Origin blog.csdn.net/crazy_tan/article/details/130662141