单链表的几个常见面试题
获取到单链表的节点的个数(如果是带头节点的链表,需求不统计头节点)
public static int getLength(Node head){
if (head.next == null) {
return 0;
}
int length = 0;
Node cur = head.next;
while (cur != null){
length++;
cur = cur.next;
}
return length;
}
查找单链表中的倒数第k个节点(新浪面试题)
public static Node findLastIndexNode(Node head,int index) {
if (head.next == null) {
return null;
}
int size = getLength(head);
if (index <= 0 || index > size){
return null;
}
Node cur = head.next;
for (int i = 0; i < size - index; i++) {
cur = cur.next;
}
return cur;
}
单链表的反转(腾讯面试题)
注:一开始我看到题也认为很简单,但是有一位伟人告诉我不要小看这道题,具体的细节弄起来很容易忽略,就例如最不起眼的反转完成后需要将head.next指向reversHead.next。
![](https://i-blog.csdnimg.cn/blog_migrate/4499e185365e48553c524f84e0a53ad2.png)
public static void reverseList(Node head) {
if (head.next == null || head.next.next == null) {
return;
}
Node cur = head.next;
Node next = null;
Node reverseHead = new Node(0, "", "");
while (cur != null) {
next = cur.next;
cur.next = reverseHead.next;
reverseHead.next = cur;
cur = next;
}
head.next = reverseHead.next;
}
从尾到头打印单链表(百度)
思路:
方式1:先将单链表进行反转操作,然后再遍历即可,这样做的问题是会破坏原来单链表的结构,不推荐使用
方式2:可以利用栈这个数据结构,将各个节点压入栈中,然后利用栈的先进后出的特点实现逆序打印的效果
栈演示:
测试stack的使用 (在Java中可以直接调用Stack 入栈操作为stack.add(),出栈操作为stack.pop())
package com.lmh.sparsearray;
import java.util.Stack;
public class testStack {
public static void main(String[] args) {
Stack<String> stack = new Stack<>();
stack.add("jack");
stack.add("tom");
stack.add("smith");
while (stack.size() > 0){
System.out.println(stack.pop());
}
}
}
代码实现:
public static void reversePrint(Node head){
if (head.next == null){
return;
}
Stack<Node> stack = new Stack<>();
Node cur = head.next;
while(cur != null){
stack.push(cur);
cur = cur.next;
}
while (stack.size()>0){
System.out.println(stack.pop());
}
}