
第三章、链表的面试题
发布日期:2021-05-07 20:08:37
浏览次数:30
分类:精选文章
本文共 1891 字,大约阅读时间需要 6 分钟。
1、单链表的面试题
1.1、获取到单链表的节点的个数(如果是带头结点的链表,需求不统计头节点)
要获取单链表的节点个数(不统计头节点),可以从链表的头节点的下一个节点开始遍历,直到最后一个节点。每遍历一个节点,计数器加1,最后返回计数器的值。
public static int getLength(HeroNode head) { if (head.next == null) { return 0; // 空链表 } int length = 0; HeroNode cur = head.next; while (cur != null) { length++; cur = cur.next; } return length;}
1.2、查找单链表中的倒数第k个结点
要找到单链表中的倒数第k个节点,可以先获取链表的总长度。如果k不在有效范围内,返回null。否则,从头节点开始遍历,直到找到倒数第k个节点。
public static HeroNode findLastIndexNode(HeroNode head, int index) { if (head.next == null) { return null; // 空链表,不能找到 } int size = getLength(head); if (index <= 0 || index > size) { return null; // index超出范围 } HeroNode cur = head.next; // 从第二个节点开始遍历 for (int i = 0; i < size - index; i++) { cur = cur.next; } return cur;}
1.3、单链表的反转
要将单链表反转,可以使用辅助指针来逐个节点连接到新链表的前面。
public static void reversetList(HeroNode head) { if (head.next == null || head.next.next == null) { return; // 链表长度为1或0,无需反转 } HeroNode cur = head.next; // 从第二个节点开始 HeroNode next = null; // 保存当前节点的下一个节点 HeroNode reverseHead = new HeroNode(0, ""); // 新的头节点 while (cur != null) { next = cur.next; // 保存当前节点的下一个节点 cur.next = reverseHead.next; // 将当前节点的下一个节点指向新链表的前面 reverseHead.next = cur; // 将当前节点连接到新链表 cur = next; // 移动到下一个节点 } head.next = reverseHead.next; // 将原链表的下一个节点指向新链表的前面}
1.4、从尾到头打印单链表
要从尾到头打印单链表,可以使用栈数据结构,将节点压入栈中,然后弹出栈,按顺序打印。
public static void reversePrint(HeroNode head) { if (head.next == null) { return; // 空链表 } Stackstack = new Stack<>(); // 创建栈 HeroNode cur = head.next; // 从第二个节点开始 while (cur != null) { stack.push(cur); // 将节点压入栈 cur = cur.next; // 移动到下一个节点 } while (stack.size() > 0) { System.out.println(stack.pop()); // 弹出栈,按逆序打印 }}