删除单向链表的指定节点

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def removeElements(self, head, val):
        """
        :type head: ListNode
        :type val: int
        :rtype: ListNode
        """
        templist=ListNode(-1)
        templist.next=head
        cur=templist
        while cur!=None and cur.next!=None:
            if cur.next.val==val:
                cur.next=cur.next.next
            else://不是直接cur=cur.next可以解决连续两个都是目标节点
                cur=cur.next
        return templist.next
在开头增加一个无关的节点可以解决开头就是指定的节点

猜你喜欢

转载自blog.csdn.net/hai008007/article/details/80188658