剑指offer之删除链表的结点(C++/Java双重实现)

1.题目描述

给定单向链表的头指针和一个要删除的节点的值,定义一个函数删除该节点。
返回删除后的链表的头节点。
注意:此题对比原题有改动
示例 1:
输入: head = [4,5,1,9], val = 5
输出: [4,1,9]
解释: 给定你链表中值为 5 的第二个节点,那么在调用了你的函数之后,该链表应变为 4 -> 1 -> 9.
示例 2:
输入: head = [4,5,1,9], val = 1
输出: [4,5,9]
解释: 给定你链表中值为 1 的第三个节点,那么在调用了你的函数之后,该链表应变为 4 -> 5 -> 9.
说明:
题目保证链表中节点的值互不相同
若使用 C 或 C++ 语言,你不需要 free 或 delete 被删除的节点

在这里插入图片描述

2.问题分析:

主要是分为4种情况
1.删除的结点在头部
2.删除的结点在尾部
3.删除的结点在中间
4.没有需要删除的结点

3.代码实现

3.1C++代码
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* deleteNode(ListNode* head, int val) {
     if(head == NULL) {
        return NULL;
    }
    if(head->val == val) {//删除的结点在头部
        return head->next;
    }
    struct ListNode* pre = head;
    while ((pre->next != NULL) && (pre->next->val != val)){
        pre = pre->next;
    }
    if(pre->next != NULL) {
        pre->next = pre->next->next;
    }
    return head;
    }
};
3.2Java代码:
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode deleteNode(ListNode head, int val) {
    if(head == null) {
        return null;
    }
    if(head.val == val) {
        return head.next;
    }
    ListNode pre = head;
    while ((pre.next != null) && (pre.next.val != val)){
        pre = pre.next;
    }
    if(pre.next != null) {
        pre.next = pre.next.next;
    }
    return head;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_45737068/article/details/107112374