文章目录
前言
为了更深入的理解无头单向链表,我将和大家分享几道关于它的面试题。
1.删除链表中所包含value值的所有节点
力扣链接如下:
link
1.1思路讲解
1.首先判断链表是否为空
2.定义cur=head.next和prev=head使用cur遍历整个链表进行删除目标节点
3.最后判断头节点是否为目标节点,进行处理
1.2具体实现
class Solution {
public ListNode removeElements(ListNode head, int val) {
if(head==null){
return null ;
}
ListNode pre=head;
ListNode cur=head.next;
while(cur!=null){
if(cur.val==val){
cur=cur.next;
pre.next=cur;
}else{
cur=cur.next;
pre=pre.next;
}
}
if(head.val==val){
head=head.next;
}
return head;
}
}
2.单链表的逆置
力扣链接如下:
link
2.1思路讲解
1.找到要反转的cur
2.使用头插法
3.使用curNext记录未修改之前的值
2.2具体实现
class Solution {
public ListNode reverseList(ListNode head) {
if(head==null){
return null;
}
if(head.next==null){
return head;
}
ListNode cur=head.next;
head.next=null;
while(cur!=null){
ListNode curNext=cur.next;
cur.next=head;
head=cur;
cur=curNext;
}
return head;
}
}
3.获取链表的中间节点
力扣链接:
link
3.1 思路讲解
1.快慢指针法,快指针走两步,慢指针走一步,当快指针走到尾部的时候,慢指针所在位置就是中间节点
原理:fast的速度是slow的二倍,时间相同,当fast走到终点时,slow就在中间位置
2.判断条件fast!=null&&fast.next!=null分别对应偶数和奇数链表
3.2具体实现
class Solution {
public ListNode middleNode(ListNode head) {
ListNode slow=head;
ListNode fast=head;
while(fast!=null&&fast.next!=null){
fast=fast.next.next;
slow=slow.next;
}
return slow;
}
}
4.获取链表倒数第K个节点
4.1思路讲解
1.fast先走k减一步
2.fast和slow一起走
3.fast走到最后slow所在的位置就是倒数第k个节点
4.2具体实现
public ListNode findKthToFail(int k){
if(k<=0){
return null;
}
ListNode fast=head;
ListNode slow=head;
int count=0;
while(count!=k-1){
if(fast.next!=null){
fast=fast.next;
count++;
}else{
return null;
}
}
while(fast.next!=null){
fast=fast.next;
slow=slow.next;
}
return slow;
}
5.合并有序链表
力扣链接:
link
5.1思路讲解
1.创建一个虚拟节点newHead
把list1和list2中的值进行比较,尾插到newHead后面
2.创建一个tmp中间变量记录newHead
但有可能一个链表走完了,一个链表还没结束,这时候只需把没结束的链表中的后面节点接到tmp后面即可
3.返回newHead.next即为所求
5.2具体实现
class Solution {
public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
ListNode newHead=new ListNode(-1);
ListNode tmp=newHead;
while(list1!=null&&list2!=null){
if(list1.val<list2.val){
tmp.next=list1;
list1=list1.next;
tmp=tmp.next;
}else{
tmp.next=list2;
list2=list2.next;
tmp=tmp.next;
}
}
if(list1!=null){
tmp.next=list1;
}
if(list2!=null){
tmp.next=list2;
}
return newHead.next;
}
}