链表面试题——带图解

1. 删除链表中等于给定值 val 的所有节点。 OJ链接

class Solution {
    public ListNode removeElements(ListNode head, int val) {
        if(head == null){
            return null;
        }
        ListNode cur = head.next;
        ListNode prev = head;
        while (cur != null) {
            if (val == cur.val){
                prev.next= cur.next;
                cur = cur.next;

            }else{
                prev = cur;
                cur = cur.next;
            }
        }
        if(head.val == val){
            head = head.next;
 
        }
        return head;
    }
}
2. 反转一个单链表。 OJ链接

 

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. 给定一个带有头结点 head 的非空单链表,返回链表的中间结点。如果有两个中间结点,则返回第二个中间结点。OJ链接

 

class Solution {
    public ListNode middleNode(ListNode head) {
        if(head.next == null){
            return head;
        }
        ListNode fast = head;
        ListNode slow = head;
        while(fast!=null && fast.next!=null){
            fast = fast.next.next;
            slow = slow.next;
        }
        return slow;
    }
}

 4. 输入一个链表,输出该链表中倒数第k个结点。 OJ链接

 

public class Solution {
    public ListNode FindKthToTail(ListNode head,int k) {
        if(k <= 0||head == null){
            return null;
        }

        ListNode fast = head;
        ListNode slow = head;

        while(k -1 > 0){
            if(fast.next==null){
                return null;
            }
            fast = fast.next;
            k--;
            
        }
        while (fast.next != null){
            fast = fast.next;
            slow = slow.next;
        }
        return slow;
    }
}
5. 将两个有序链表合并为一个新的有序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。 OJ链接

 

class Solution {
    public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
        ListNode head = new ListNode(-1);
        ListNode cur = head;
        while(list1!=null &&list2!=null){
            if(list1.val <= list2.val){
                cur.next = list1;
                cur = cur.next;
                list1 = list1.next;
            }else{
                cur.next = list2;
                cur = cur.next;
                list2 = list2.next;
            }   
        }
        cur.next = list1 == null ? list2 : list1;
        return head.next;
    }  
}

还有哦~ 希望我的图解能帮助各位理解链表的问题 下篇博客

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值