首页 > 其他 > 详细

【LeetCode】面试题18. 删除链表的节点

时间:2020-05-29 15:26:55      阅读:46      评论:0      收藏:0      [点我收藏+]

题目:

技术分享图片

思路:

单链表的删除(无重复元素),特殊情况链表为空或链表头元素为要删除的元素(此时返回的head修改了),其它情况记录上个节点和当前节点,删除后返回head即可。

代码:

Python

# 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
        """
        if head is None:
            return None
        if head.val == val:
            return head.next
        preElem = head
        nowElem = head.next
        while nowElem is not None:
            if nowElem.val == val:
                preElem.next = nowElem.next
                nowElem.next = None
                return head
            else:
                preElem = nowElem
                nowElem = nowElem.next
        return head

相关问题

【LeetCode】面试题18. 删除链表的节点

原文:https://www.cnblogs.com/cling-cling/p/12986009.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!