前后指针

要点

1.前后指针可以用在处理链表倒数第n个节点相关的问题。
2.删除链表元素多使用前后指针,和快慢指针相似。

例题

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

class Solution:
    def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:
        dumpy=ListNode(next=head)
        temp=0
        front=dumpy
        rear=dumpy
        while temp<=n:
            front=front.next
            temp+=1
        while front:
            front=front.next
            rear=rear.next
        rear.next=rear.next.next
        return dumpy.next

class Solution:
    def deleteDuplicates(self, head: Optional[ListNode]) -> Optional[ListNode]:
        cur=head
        while cur and cur.next:
            if cur.val==cur.next.val:
                cur.next=cur.next.next
            else:
                cur=cur.next
        return head

class Solution:
    def deleteDuplicates(self, head: Optional[ListNode]) -> Optional[ListNode]:
        dumpy=ListNode(next=head)
        front=dumpy
        cur=head
        while cur and cur.next:
            while cur.next and cur.next.val==cur.val:
                cur=cur.next
            if front.next is not cur:
                front.next=cur.next
                cur=cur.next
            else:
                front=cur
                cur=cur.next
        return dumpy.next