算法-单链表练习题

题目1:

单链表(有头结点)的反转

代码:

思路:从头到尾遍历原链表,每遍历一个节点,就将其取出,并用头插法插在新链表上,最后再拼上头结点

public static void reversetList(HeroNode head) {
    // 当链表为空/只有一个时,不需反转
    if (head.next == null || head.next.next == null) {
        return;
    }
    // 定义一个辅助指针,遍历原链表
    HeroNode cur = head.next;
    // 用于动态指向 当前节点【cur】的 下一个节点
    HeroNode next = null;
    // 新链表的头结点
    // public HeroNode(int no, String name, String nickname){}
    HeroNode reversetHead = new HeroNode(0, "", "");
    while (cur != null) {
        next = cur.next;
        cur.next = reversetHead.next;
        reversetHead.next = cur;
        cur = next;
    }
    // 将head.next 指向 reverseHead.next , 实现单链表的反转
    head.next = reversetHead.next;
}

题目2:

从尾到头打印单链表(有头结点)

代码:

思路1:先将单链表进行反转操作,然后再遍历即可 【会破坏原单链表的结构,不推荐】

思路2:利用栈的先进后出,将各个节点压入栈中再打印出栈

public static void reversetPrint(HeroNode head) {
    // 判空
    if(head.next == null)
        return;
    // 创建一个栈
    Stack<HeroNode> stack = new Stack();
    HeroNode temp = head.next;
    // 将链表所有节点入栈
    while (temp != null) {
        stack.push(temp); // 节点 入栈
        temp = temp.next; // 节点后移
    }
    // 所有节点依次打印出栈
    while(stack.size() >0) {
        System.out.println(stack.pop());
    }
}

题目3:

合并两个有序的单链表(有头结点),合并之后的链表依然有序

代码:

思路1:两个有序链表1和2,视1为主链,遍历2中的元素并插入1中

public static void twoLinkedList(Node head1, Node head2) {
    // 如果两个链表均为空,则无需合并,直接返回
    if((head1.next == null && head2.next == null) || head2.next == null) {
        return;
    }
    // 如果其中head2为空
    else if(head1.next == null) {
        head1.next = head2.next;
    }
    else{
        Node cur2 = head2.next;
        Node cur1 = head1.next;
        Node next2 = null;
        while(cur2 != null){
            while(cur2.no <= cur1.next.no) {
                next2 = cur2.next;
                cur2.next = cur1.next;
                cur1.next = cur2;
                cur2 = next2;
            }
            cur1 = cur1.next;
            if(cur1.next == null) {
                cur1.next = cur2;
                break;
            }
        }
    }
}

思路2: 新建链表3,分别比较1和2中的元素,不断插入最小结点直至1和2结点耗尽

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值