leetcode刷题笔记十九 删除链表的倒数第N个节点 Scala版本

leetcode刷题笔记十九 删除链表的倒数第N个节点 Scala版本

源地址:19. 删除链表的倒数第N个节点

问题描述:

Given a linked list, remove the n-th node from the end of list and return its head.

Example:

Given linked list: 1->2->3->4->5, and n = 2.

After removing the second node from the end, the linked list becomes 1->2->3->5.

Note:

Given n will always be valid.

代码补充:

//本题与查找倒数n个节点的方法基本一致

object Solution {    
    def removeNthFromEnd(head: ListNode, n: Int): ListNode = {
        // 对于空串 直接返回
        if (n == 0) return head
        
        //设置两个指针指向链表头
        var nodeLeft = head
        var nodeRight = head
        
        //右侧指针移动n位,至此左右指针相差n+1
        for(i <- 0 to n-1)  {
             nodeRight = nodeRight.next
        }
        
        //右侧指针移动后,主要有两种情况
        //此处处理的是右侧指针达到链表尾
        //这种情况下,相当于head为倒数n位,这样我们只需要去掉head
        if (nodeRight == null) return head.next
        
        //如果右侧指针未达到链表尾,左右指针保持距离向前
        //直到右侧指针到达末尾
        while(nodeRight.next != null){
            nodeRight = nodeRight.next
            nodeLeft  = nodeLeft.next 
        }
        
        //将倒数n个节点去掉
        nodeLeft.next = nodeLeft.next.next
        head
    }
    
}
原文地址:https://www.cnblogs.com/ganshuoos/p/12734601.html