Leedcode11 链表分割

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

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

方法一:

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;
    }
}

方法二:栈

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;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值