首页 > 其他 > 详细

19. 删除链表的倒数第N个节点-链表(leetcode)

时间:2020-03-28 00:51:51      阅读:52      评论:0      收藏:0      [点我收藏+]

技术分享图片

 

 

收获:

  1.在python中对链表中节点进行操作时:

    a) 从前 我直接 return  head (错误)

    b)现在由于怕 head 会被修改,所以要设  point = Listnode(-1)            return point

  2. 我自己只想出了两遍遍历,收获了一遍遍历的思路:  双指针

    a)  使 fast 与 slow 之间始终隔着 n,以例题为例,n=2,需要保证 fast = 5 时候 slow = 3 , slow.next = slow.next.next 

    b) 我记得之前学C的数据结构,需要借助middle 来传递 .next,like   a = point.next;  point.next = a.next; a.next = None

       不知道在python 里面可以直接使用 slow.next = slow.next.next 

    

 

代码1)   用了两次遍历的方法

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

class Solution:
    def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
        tail = head
        count = 0
        while tail :
            tail = tail.next 
            count +=1
        print(n)
        n = count - n 
        print(n)
        if n ==0:
            return head.next
        else:
            a = head
            m = n-1
            point = 0
            while point < m:
                head = head.next 
                point +=1
            target = head.next
            head.next = target.next
            target.next = None
            return a 
            

 代码2)一次遍历  思路借鉴leetcode官方题解

 

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

class Solution:
    def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
        if head.next == None:
            return None

        point = ListNode(-1)
        point.next = head
        fast = slow = point 
        i = 0
        while fast.next:
            fast = fast.next
            i+=1   # 2 3 4-2 5-3
            if i>n:
                slow = slow.next
        slow.next = slow.next.next
        return point.next
 
下图链接为
 
技术分享图片

 

 

19. 删除链表的倒数第N个节点-链表(leetcode)

原文:https://www.cnblogs.com/ChevisZhang/p/12585100.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!