单链表 面试题
求单链表有效节点的个数:
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;
}
查找链表中倒数第K个节点【新浪面试题】
思路:
1)构造一个方法 接受head头节点 并接受一个index(表示倒数第index个节点)
2)遍历链表得到当前有效节点个数 size=getLength()
3)从第一个节点开始遍历 到size-index 结束 即可找到倒数第index个节点
4)找到即返回该节点 否则 返回空
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;
}
HeroNode cur=head.next;
for (int i=0;i<size-index;i++){
cur=cur.next;
}
return cur;
}
反转单链表【腾讯面试题 有点绕 建议画图理解】
思路:
1)新建一个resHead头节点
2)从头遍历原链表 每遍历一个节点就把它取下 添加到新的链表resHead的最前端
3)最后将原链表的head.next=resHead.next
public static void reservesLinkedList(HeroNode head){
if (head.next==null||head.next.next==null){//链表为空或只有一个节点 不必反转
return;
}
HeroNode resHead =new HeroNode(0,"","");
HeroNode cur=head.next;//辅助变量
HeroNode next=null;//用来保存cur的下一个节点 防止断链
while(cur!=null){
next=cur.next;
cur.next=resHead.next;//cur是被取下的节点 头插法
resHead.next=cur;//以上两行是头插法标配 画图更好理解!
cur=next;//cur后移 实现遍历
}
head.next=resHead.next;
}
逆序打印单链表【百度面试题】
方式1:先将链表反转后打印(破坏了链表结构××)
方式2:利用栈 先进后出的特性
public static void resPrint(HeroNode head){
if (head.next==null){
return;
}
Stack<HeroNode> stack = new Stack<>();//新建一个栈
//将链表的各个节点以此push入栈
HeroNode cur=head.next;
while (cur!=null){
stack.push(cur);
cur=cur.next;
}
//将栈中数据依次pop出栈
while (stack.size()>0){
System.out.println(stack.pop());
}
}
合并两个有序的单链表 合并之后的链表依然有序:
//【递归方法】
public static HeroNode mergeLinkedList(HeroNode head1, HeroNode head2) {
if (head1 == null && head2 == null) {
return null;
}
if (head1 == null) {
return head2;
}
if (head2 == null) {
return head1;
}
//创建一个新的头节点
HeroNode head = null;
if (head1.no < head2.no) {
head = head1;
head.next = mergeLinkedList(head1.next, head2);
} else {
head = head2;
head.next = mergeLinkedList(head1, head2.next);
}
return head;
}
}