iT邦幫忙

第 12 屆 iThome 鐵人賽

DAY 18
0
Software Development

刷刷題 or Alan Becker's game 製作 is a question 系列 第 18

(Medium) 19. Remove Nth Node From End of List

  • 分享至 

  • xImage
  •  

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.

Follow up:

Could you do this in one pass?

        while rabbit.next != None:
            rabbit = rabbit.next
            turtle = turtle.next

應該改成 兔子偷跑 先偷跑 n 步

        for _ in range(n):
            rabbit = rabbit.next
            #print(dummyNode)
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
        dummyNode = ListNode()
        # DummyNode (0)
        dummyNode.next = head
        # DummyNode -> 1 -> 2 -> 3 -> 4 -> 5 
        # 0 -> 1 -> 2 -> 3 -> 4 -> 5
        turtle = dummyNode
        rabbit = dummyNode
        
        for _ in range(n):
            rabbit = rabbit.next
            #print(dummyNode)
          
        print(rabbit)
        # rabbit's position : 3 
        print(rabbit.val)
        
        while rabbit.next != None:
            rabbit = rabbit.next
            turtle = turtle.next
            #print(dummyNode)
            print(rabbit)
            print(turtle)
        #print('before:',dummyNode)    
        turtle.next = turtle.next.next # 以 ex 來看 , 修改下一步(4)為下下步(5)
        #print('after:',dummyNode)
        return  dummyNode.next

上一篇
(Medium)18. 4Sum
下一篇
(Easy) 20. Valid Parentheses
系列文
刷刷題 or Alan Becker's game 製作 is a question 30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言