删除链接列表中的第n至第m个节点

时间:2019-06-06 03:31:23

标签: python python-3.x

给出一个链表,删除第n个到第m个节点,返回head的索引。 标签以0开头。

我找到了此问题的Java版本,因此将其转换为Python,但我不太了解代码的逻辑,有人可以解释它的工作原理(例如逐行)吗?谢谢。

class Solution:
    """
    @param head: The first node of linked list
    @param n: the start index
    @param m: the end node
    @return: A ListNode
    """
    def deleteNode(self, head, n, m):

        pre = head
        cur = head

        if n == 0:
            for j in range(0, m):
                cur = cur.next
            return cur.next

        for i in range(0,n-1):
            pre = pre.next

        for j in range(0,m):
            cur = cur.next

        pre.next = cur.next

        return head
Input: head = 1->2->3->4->5->null, n = 1, m = 2
Output: 1->4->5->null

1 个答案:

答案 0 :(得分:0)

class Solution:
    """
    @param head: The first node of linked list
    @param n: the start index
    @param m: the end node
    @return: A ListNode
    """
    def deleteNode(self, head, n, m):

        pre = head #a linked list is only accesible thtough the head, so you need 
        cur = head #to declare both as the same 

        if n == 0: #only if you need to eliminate the first element
            for j in range(0, m): #range is not inclusive, so you will stop at m-1
                cur = cur.next  #so this is acctually m - 1 
            return cur.next #return actually with the m value (alternatively you could simply do 
           # for j in range(0, m+1):
           #      cur = cur.next
           # return cur

         for i in range(0,n-1): #if the n value is not at the beginning 
            pre = pre.next #simply move on to the next node 

        for j in range(0,m): #since you are starting on the nth node, skip the value, erasing it in cur
            cur = cur.next

        pre.next = cur.next #join the two results 

        return head #return the head, since the pointer in memory shares the same result