美文网首页
删除链表的节点

删除链表的节点

作者: 0error_ | 来源:发表于2020-03-29 00:08 被阅读0次

    链表里的节点删来删去,单独整理一篇。

    1. 重复的都删掉一个不剩

    剑指offer里面的题:在一个排序的链表中,存在重复的结点,请删除该链表中重复的结点,重复的结点不保留,返回链表头指针。 例如,链表1->2->3->3->4->4->5 处理后为 1->2->5

    找了很多个找到一个适合我理解的大神题解,大神用java写的,思路也很清晰:https://blog.nowcoder.net/n/589a7c67248b4ec4afcf321413424d57?f=comment

    改写python版:
    注意辅助头结点一定要有啊!刚开始我傻乎乎头结点设了个None。。

    class Solution:
        def deleteDuplication(self, pHead):
            # write code here\
            if not pHead or not pHead.next: return pHead
            head = ListNode(0)
            head.next = pHead
            pre = head
            cur = head.next
            while cur:
                if cur.next and cur.next.val == cur.val:
                    while cur.next and cur.next.val == cur.val:
                        cur = cur.next
                    cur = cur.next
                    pre.next = cur
                else:
                    pre = cur
                    cur = cur.next
            return head.next
    
    2. 重复的删掉,只剩一个

    leetcode83:删除排序链表中的重复元素

    给定一个排序链表,删除所有重复的元素,使得每个元素只出现一次。 image.png

    这道题比较好理解,重复的只保留1个。

    class Solution:
        def deleteDuplicates(self,head):
            if not head: return None
            p = head
            while p.next:
                if p.val == p.next.val:
                    p.next = p.next.next
                else:
                    p = p.next
            return head
    

    也有大佬用递归,回头补上(¦3[▓▓]

    3. 删除指定的节点

    leetcode237:请编写一个函数,使其可以删除某个链表中给定的(非末尾)节点,你将只被给定要求被删除的节点。
    现有一个链表 -- head = [4,5,1,9],它可以表示为:

    image.png
    示例 1:
    输入: head = [4,5,1,9], node = 5
    输出: [4,1,9]
    解释: 给定你链表中值为 5 的第二个节点,那么在调用了你的函数之后,该链表应变为 4 -> 1 -> 9.
    示例 2:
    输入: head = [4,5,1,9], node = 1
    输出: [4,5,9]
    解释: 给定你链表中值为 1 的第三个节点,那么在调用了你的函数之后,该链表应变为 4 -> 5 -> 9.
    https://leetcode-cn.com/problems/delete-node-in-a-linked-list/

    大神题解:https://leetcode-cn.com/problems/delete-node-in-a-linked-list/solution/delete-node-in-a-linked-list-zhi-jie-xiu-gai-by-jy/
    大神讲得很清楚,这个题刚开始我还在找head在哪里= =

    class Solution:
        def deleteNode(self, node):
            """
            :type node: ListNode
            :rtype: void Do not return anything, modify node in-place instead.
            """
            node.val = node.next.val
            node.next = node.next.next
    

    相关文章

      网友评论

          本文标题:删除链表的节点

          本文链接:https://www.haomeiwen.com/subject/cqweuhtx.html