个人简介
😎大家好,我是辉code⬅️⬅️往期文章可以查看我的主页进行观看哦
👊因为坚持才有幸运的机会!!
❤️点赞随意,关注随缘,你的支持是我坚持的动力!
👊此文章的专栏 数据结构
前言
跟着B站尚硅谷老韩的数据结构进行学习,所做的笔记。若是对你有用,点赞,关注支持一下!!我会持续更新。
单链表的面试题
1.求单链表中有效节点的个数
//单链表的常见面试题有如下:
// 求单链表中有效节点的个数:遍历链表,当为空时,遍历结束
public static int getLength(HeroNode head){
int length = 0;//返回值
HeroNode temp =head.next;
while (true){
if (temp == null){
break;
}else if (temp != null){
length++;
}
temp = temp.next;
}
return length;
}
2.查找单链表中的倒数第k个结点
// 查找单链表中的倒数第k个结点 【新浪面试题】:获取长度length,和倒数第K个节点(index) 遍历length-index次
//参数,一个head头节点,一个index索引
public static HeroNode getLastIndexHeroNode(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;//例如size为3 index为倒数第一即为1,则3-1=2 ,要循坏两次
for (int i = 0; i < size - index; i++) {
temp = temp.next;
}
return temp;
}
3.反转单链表
思路:
- 先定义一个节点 reverseHead = new HeroNode();
- 从头到尾遍历原来的链表,每遍历一个节点,就将其取出,并放在新的链表reverseHead 的最前端.
- 原来的链表的head.next = reverseHead.next
//单链表反转,参数为需要反转的头指针
public static void reverseList(HeroNode head){
//定义一个当前临时当量,下一个临时变量,反转链表
HeroNode cur =head.next;
HeroNode next =null;
HeroNode reverseList =new HeroNode(0,"","");
//校验一下
if (head.next ==null || head.next.next==null){
return ;
}
//通过循环
while (cur!=null){
next = cur.next; //保存下一个数据
//将当前的cur插入到反转链表的最前面
cur.next = reverseList.next;
reverseList.next = cur;
cur =next; //开始下一个赋值,进行插入
}
//将原来的头指针指向反转链表的同数据
head.next = reverseList.next;
}
}
4.单链表反转打印
要求方式1:反向遍历 。
方式2:Stack栈
//单链表反转打印
public static void revesePrint(HeroNode head){
//定义栈,将单链表的数据加入其中,然后进行打印
//校验
if (head.next == null ){
System.out.println("链表为空");
return;
}
HeroNode cur = head.next;
Stack<HeroNode> stack = new Stack<>();
while (cur!=null){
stack.push(cur);
cur= cur.next;
}
while (stack.size()>0){
System.out.println(stack.pop());
}
}
5.合并两个有序的单链表,合并之后的链表依然有序
思路:
1.将head1每个数的与head2遍历相比若是成立,找到比head2小的元素的前一个值的位置。
2.条件成立则
● temp.next = temp2.next;
● temp2.next =temp;
● temp = next;
// 合并两个有序的单链表,合并之后的链表依然有序
public static void mergerLinkedList(HeroNode head1,HeroNode head2){
//校验
if (head1.next ==null || head2.next ==null){
return;
}
//先定义一个新链表,并指向其中一个链表的头
HeroNode orderHero = new HeroNode(0,"","");
orderHero.next = head2.next;
//定义两个临时变量
//1.拿head1的第一个遍历 head2 并且插入
//2.直至head1全部遍历完,
HeroNode temp = head1.next; //
HeroNode temp2 = head2;
HeroNode next = null;
while (temp != null){ //遍历head1 每一个元素
next = temp.next; //指向temp值的下一个。用于保留元素
if (temp.no < temp2.next.no){ //待插入的值要小于链表指向的下一个值
temp.next = temp2.next;
temp2.next =temp;
temp = next;
}else if (temp.no == temp2.next.no){
System.out.println("这是相同的值不能插入");
break;
}else if (temp.no > temp2.next.no){
temp2 = temp2.next;
}
}
}
总结
若是有所收获,点赞,关注支持一下!!谢谢!!❤️❤️❤️❤️❤️