单链表的其他操作

这篇博客介绍了两种链表操作:如何高效地合并两个有序链表以及如何逆序打印链表。在合并链表时,通过比较节点数值并依次插入新链表实现。逆序打印则利用栈的特性,先将链表元素压栈,再依次弹出并打印。这些方法在链表处理中非常实用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.合并有序链表

  private static SingleLinkedList mergeLinkedList(SingleLinkedList list1,SingleLinkedList list2){
        HeroNode head1 = list1.getHead();
        HeroNode head2 = list2.getHead();
        if(head1.next == null && head2.next == null){
            System.out.println("两个链表都为空...");
            return null;
        }
        if(head1.next == null){
            return list2;
        }
        if(head2.next == null){
            return list1;
        }

        HeroNode temp1 = head1.next;//直接指向第一个节点
        HeroNode temp2 = head2.next;
        SingleLinkedList mergeList = new SingleLinkedList();
        HeroNode head = mergeList.getHead();
        HeroNode temp = head.next;
        while(temp1 != null && temp2 != null){
            if(temp1.no <= temp2.no){
                //第一个链表的节点比较小,创建一个新链表存储
                mergeList.add(temp1);
                temp = temp.next;
                temp1 = temp1.next;
            }else{
                mergeList.add(temp2);
                temp = temp.next;
                temp2 = temp2.next;
            }
        }
        if(temp1 == null){
            //把temp2接下来的元素全部接进去
            temp.next = temp2;
        }else{
            temp.next = temp1;
        }
        return mergeList;
    }

2.逆序打印链表

    /*
        分析:
            1.可以使用先反转链表,然后打印,然后在反转回去的方法,但是这种如果链表长就不好了;
            2.使用栈来存储链表,然后在从栈中往外取数据就好了;
        使用栈的方式来解决问题的思路:
            1.先遍历链表,每次去到一个数据,就把他存入栈中,知道末尾
            2.当temp.next == null,就代表走到了链表的末尾,这个时候就可以使用pop操作往外面取出数据并且打印
     */
    public void reversePrint(){
        if(head.next == null){
            System.out.println("链表为空...");
            return;
        }

        Stack<HeroNode> stack = new Stack<HeroNode>();
        HeroNode temp = head.next;//直接指向第一个元素
        while(true){
            stack.push(temp);
            if(temp.next == null){
                break;
            }
            temp = temp.next;
        }

        //到这个位置,链表的元素已经全部放到栈中了,接下来就是出栈操作
        while(stack.size() > 0){
            System.out.println(stack.pop());
        }
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值