此篇文章只是为了讲解链表常见面试题,与前面一篇【Java数据结构与算法–链表(Linked List)文章链接】文章是接着的。前一篇文章也有此部分代码,是非常完整的,是拿来就能用的。
单链表的常见面试题有如下:
1)求单链表中有效节点的个数。
代码如下:
// 获取链表的长度(有效节点的个数)
public int getLength(){
if (head.next==null){
return 0;
}
HeroNode current = head.next;
int length = 0;
while (current!=null){
length++;
current = current.next;
}
return length;
}
2)查找单链表中的倒数第 k 个结点(新浪面试题)。
代码如下:
//思路
//1. 编写一个方法,接收 head 节点,同时接收一个 index
//2. index 表示是倒数第 index 个节点
//3. 先把链表从头到尾遍历,得到链表的总的长度 getLength
//4. 得到 size 后,我们从链表的第一个开始遍历 (size-index)个,就可以得到
//5. 如果找到了,则返回该节点,否则返回 null
public HeroNode findLastIndexNode(int index) {
//判断如果链表为空,返回 null
if (head.next == null) {
return null;
}
//第一个遍历得到链表的长度(节点个数)
int length = getLength();
//第二次遍历 length-index 位置,就是我们倒数的第 K 个节点
// 校验
if (index > length || index <= 0) {
return null;
}
HeroNode current = head.next;
for (int i = 0; i < length - index; i++) {
current = current.next;
}
return current;
}
3)单链表的反转(腾讯面试题)。
思路分析图解:
代码实现:
// 单链表的反转
public void reverseLinked() {
if (head.next == null || head.next.next == null) {
return;
}
// 指向链表的第一个节点
HeroNode current = head.next;
// 用作备份下一个节点
HeroNode next = null;
HeroNode reverseNode = new HeroNode(0, "", "");
while (current != null) {
next = current.next;
current.next = reverseNode.next;
reverseNode.next = current;
current = next;
}
this.head = reverseNode;
}
4)从尾到头打印单链表 【百度,要求方式 1:反向遍历 。 方式 2:Stack 栈】
思路分析图解:
代码实现:
// 单链表逆向打印
public void reversePrint() {
if (head.next == null) {
return;
}
Stack<HeroNode> nodeStack = new Stack<>();
HeroNode current = head.next;
// 将链表的所有节点入栈
while (current != null) {
nodeStack.push(current);
current = current.next;
}
// 将链表的所有节点出栈
while (nodeStack.size() > 0) {
System.out.println(nodeStack.pop());
}
}
完整代码请参照上一篇的【Java数据结构与算法–链表(Linked List)】
连接奉上:文章连接