数据结构——单链表在面试中可能遇到的问题(Java)

数据结构——单链表在面试中可能遇到的问题(Java)

博客说明

文章所涉及的资料来自互联网整理和个人总结,意在于个人学习和经验汇总,如有什么地方侵权,请联系本人删除,谢谢!

求单链表中有效节点的个数

思路

遍历,注意不需要统计头结点

代码
/**
 * @param head 链表的头结点
 * @return 有效个数
 */
public static int getLength(HeroNode head){
    if (head.next == null){
        return 0;
    }
    int length = 0;
    HeroNode temp = head.next;
    while (temp != null){
        length++;
        temp = temp.next;
    }
    return length;
}

查找单链表中的倒数第k个节点

思路

第一次遍历获取有效节点的个数,第二次遍历确定倒数元素的位置

代码
public static HeroNode findLastK(HeroNode head,int index){
    if (head.next == null){
        return null;
    }
    int size = getLength(head);
    if (index <= 0 || index > size){
        return null;
    }
    HeroNode temp = head.next;
    for (int i=0;i<size-index;i++){
        temp = temp.next;
    }
    return temp;
}

单链表的反转

思路

首先定义一个新的链表

遍历原来的链表,取出每一个节点都将它放到新链表的第一个,再把链表整个还回去

代码
public static void reverseList(HeroNode head){
    if (head.next == null || head.next.next == null){
        return;
    }
    HeroNode temp = head.next;
    HeroNode next = null;//指向当前节点temp的下一个节点
    HeroNode reverseHead = new HeroNode(0,"",""); //new一个新的链表的头结点
    //遍历
    while (temp != null){
        next = temp.next;
        temp.next = reverseHead.next;//将temp的下一个节点指向新链表的头结点的下一个节点(最前端)
        reverseHead.next = temp;//连接到新的链表上
        temp = next;
    }
    //还回
    head.next = reverseHead.next;
}
结果

在这里插入图片描述

从尾到头打印单链表的节点

这个和我们上面有点相似,不过这个会破坏单链表的结构

思路

可以用栈,将各个元素压入栈中,利用栈先进后出的特点来实现

public static void reversePrint(HeroNode head){
        if (head.next == null){
            return;
        }
        //创建栈
        Stack<HeroNode> stack = new Stack<HeroNode>();
        HeroNode temp = head.next;
        while (temp != null){
            stack.push(temp);  //入栈
            temp = temp.next;
        }
        //出栈
        while (stack.size() > 0){
            System.out.println(stack.pop());
        }
    }
结果

在这里插入图片描述

完整的代码放在这里

https://blog.csdn.net/qq_45163122/article/details/105011781

感谢

百度百科

万能的网络

以及勤劳的自己

发布了177 篇原创文章 · 获赞 456 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/qq_45163122/article/details/105013655
今日推荐