合并两个有序的链表, 合并后的链表也是有序的(Java实现)

public class LRU {
    static int num=0;
    //用链表实现一个LRU缓存(大小为100)中添加一个数据
    public static Node addNewValue(Node head,Node x){
        Node ptr=head;
        num++;
        //1.遍历链表查看数据是否已经存在
        while(ptr!=null&&ptr.next.next!=null) {
            //2.如果存在,删除当前结点,并在表头添加
            if (ptr.next.value == x.value) {
                ptr.next = ptr.next.next;
                x.next = head;
                head=x;
                return head;
            }
            ptr=ptr.next;
            num++;
        }
        //3.如果不存在
        //a.缓存未满,直接在表头添加
        if(num<100){
            x.next=head;
            head=x;
        }
        //b.缓存已满,删除表尾结点,在表头添加
        else{
            ptr.next=null;
            x.next=head;
            head=x;
        }
        return head;
    }
    //遍历链表(已知一个头结点,便可以遍历整个链表)
    public static void printAll(Node head){
        Node cur=head;
        while (cur.next!=null){
            System.out.print(cur.value+"->");
            cur=cur.next;
        }
        System.out.print(cur.value);
        System.out.println();
    }
    public static void main(String[] args) {
        Node head1=new Node(3,null);
        head1=new Node(3,head1);
        head1=new Node(2,head1);
        head1=new Node(1,head1);
        printAll(head1);
        Node x1=new Node(0);
        printAll(addNewValue(head1,x1));
        Node x2=new Node(2);
        printAll(addNewValue(head1,x2));
    }

}

class Node{
    int value;
    Node next;

    public Node(int value) {
        this.value = value;
    }
    public Node(int value,Node next){
        this.value=value;
        this.next=next;
    }
}

运行结果截图:
在这里插入图片描述

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值