TreeviewCopyright © aleen42 all right reserved, powered by aleen42

18. 删除链表的节点

https://leetcode-cn.com/problems/shan-chu-lian-biao-de-jie-dian-lcof/

Java

/*
 * @Author: Goog Tech
 * @Date: 2020-07-17 06:54:07
 * @Description: https://leetcode-cn.com/problems/shan-chu-lian-biao-de-jie-dian-lcof/
 * @FilePath: \leetcode-googtech\剑指 Offer\#18. 删除链表的节点\Solution.java
 */ 

/**
 * 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 head;
        }
        // 初始化待删除节点与其前置节点
        ListNode deletedNode = head;
        ListNode previousNode = null;
        // 判断待删除节点是否为头节点
        if(deletedNode.val==val){
            return head.next;
        }
        // 寻找待删除节点
        while(deletedNode.val!=val){
            previousNode = deletedNode;
            deletedNode = deletedNode.next;
        }
        // 通过更新指针来移除待删节点
        // 待删节点的前置节点的指针指向待删除节点的后一个节点
        previousNode.next = deletedNode.next;
        return head;
    }
}

Python

'''
@Author: Goog Tech
@Date: 2020-07-17 07:17:03
@Description: https://leetcode-cn.com/problems/shan-chu-lian-biao-de-jie-dian-lcof/solution/python-dan-zhi-zhen-by-hongge/
@FilePath: \leetcode-googtech\剑指 Offer\#18. 删除链表的节点\Solution.py
'''
# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def deleteNode(self, head, val):
        """
        :type head: ListNode
        :type val: int
        :rtype: ListNode
        """
        currentNode = head
        # 判断头节点是否为空
        if not head:
            return head
        # 判断待删节点是否为头节点
        if head.val == val:
            return head.next
        # 判断当前节点的下一个节点的下一个节点是否为待删节点
        while currentNode.next:
            if currentNode.next.val == val:
                currentNode.next = currentNode.next.next
                break
            currentNode = currentNode.next
        return head
Copyright © GoogTech 2021 all right reserved,powered by GitbookLast update time : 2021-09-15 01:55:05

results matching ""

    No results matching ""