单链表常见的面试题如下:
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;
}
2.查找单链表中倒数第k个结点【新浪面试】
思路:
1.编写一个方法接收head结点,同时接收一个index
2.index表示的是倒数第index个结点
3.先把链表从头到尾遍历,得到链表的总长度getLength
4.得到size后,我们从链表的第一个开始遍历(size - index)个
5.如果找到则返回该结点,否则返回null
// 思路:
// 1.编写一个方法接收head结点,同时接收一个index
// 2.index表示的是倒数第index个结点
// 3.先把链表从头到尾遍历,得到链表的总长度getLength
// 4.得到size后,我们从链表的第一个开始遍历(size - index)个
// 5.如果找到则返回该结点,否则返回null
public static HeroNode findLaseIndexNode(HeroNode head,int index) {
//判断链表为空,返回null
if(head.next == null) {
return null;
}
//第一个遍历得到链表的长度
int size =getLength(head);
//第二次遍历size -index 的位置,就是我们找的倒数k个结点
//先做数据的校验
if(index <=0 ||index >size) {
return null;
}
//定义一个辅助变量ford循环定位到倒数index
HeroNode cur = head.next;
for(int i =0;i<size - index;i++) {
cur =cur.next;
}
return cur;
}
3.单链表的反转【腾讯】
解题思路:
1.先定义一个节点reverseHead = newHeroNode
2.从头到尾遍历原来的链表,每遍历一个结点取出并放在reverseHead 的最前端。
3.原来链表的head.next = reverseHead .next
//将单链表进行反转
public static void reversetList(HeroNode head) {
//如果链表为空或者只有一个结点,无需反转,直接返回
if(head.next == null || head.next.next ==null) {
return ;
}
//定义一个辅助指针,帮助遍历链表
HeroNode cur = head.next;
HeroNode next = null;//指向当前结点【cur】的下一结点
HeroNode reverseHead = new HeroNode(0,"","");
//遍从头到尾遍历原来的链表,每遍历一个结点取出并放在reverseHead 的**最前端**
while(cur != null) {
next =cur.next;//暂时保存当前结点的下一结点
cur.next =reverseHead.next;//将cur的下一个结点指向新的链表的最前端
reverseHead.next = cur;//将cur连接到新的结点
cur = next;//让cur后移
}
//将head.next指向reverseHead.next,实现单链表的反转
head.next =reverseHead.next;
}
4.从尾到头打印单链表【百度】
思路:
1.上面的要求解释逆序打印单链表
2.方式一:先将单链表进行反转,然后进行遍历即可,这样做的为题是会破坏原来的单链表的结构你,不建议
3.方式二:可以利用栈这个结构,将各个节点压入到栈,然后利用栈的先进后出的特点,就实现了逆序打印的效果。
栈的演示:
package Linkdelist;
import java.util.Stack;
//演示栈的stark的基本使用
public class TestStark {
public static void main(String[] args) {
// TODO Auto-generated method stub
Stack<String> stack= new Stack();
//入栈
stack.add("jack");
stack.add("tom");
stack.add("mack");
stack.add("smith");
//取出
while(stack.size() >0) {
System.out.println(stack.pop());//pop是栈顶数据取出
}
}
}
![在这里插入图片描述](https://img-blog.csdnimg.cn/20200216200407388.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L216Y19sb3Zl,size_16,color_FFFFFF,t_70)
实现链表的逆序打印:
//.方式二:可以利用栈这个结构,将各个节点压入到**栈**,然后利用栈的先进后出的特点,就实现了逆序打印的效果。
public static void revererPrint(HeroNode head) {
if(head.next == null) {//空链表不能打印
return ;
}
//创建一个栈,将各个节点压入栈
Stack<HeroNode> stack = new Stack<HeroNode>();
HeroNode cur =head.next;
//将链表的所有结点压入栈中
while(cur != null) {
stack.push(cur);
cur = cur.next;//cur后移,压入下一个
}
//将栈中结点打印
while(stack.size()> 0) {
System.out.println(stack.pop());//先进后出
}
}