zoukankan      html  css  js  c++  java
  • [leetcode]Remove Nth Node From End of List

    简单题。唯一的小技巧是使用了指向指针的指针。

    class Solution {
    public:
        ListNode *removeNthFromEnd(ListNode *head, int n) {
            // Start typing your C/C++ solution below
            // DO NOT write int main() function
        	ListNode * forward = head;
    		ListNode ** current = &head;
            n--;
    		while (n--)
    		{
    			forward = forward->next;
    		}
    		while (forward->next != 0)
    		{
    			forward = forward->next;
    			current = &((*current)->next);
    		}
    		*current = (*current)->next; 
            return head;
        }
    };
    

    python3,使用了头结点

    # 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:
            tmp = head
            while n > 0:
                tmp = tmp.next
                n -= 1
            current = head
            dummy = ListNode(0)
            dummy.next = current
            prev = dummy
            while tmp != None:
                tmp = tmp.next
                current = current.next
                prev = prev.next
            prev.next = current.next
            return dummy.next
            
    

      

  • 相关阅读:
    第五周总结
    第四周总结
    第三周总结
    开课博客
    学习进度
    个人作业1-数组
    数组
    第一周考试总结
    团队个人冲刺第六天
    团队个人冲刺第五天
  • 原文地址:https://www.cnblogs.com/lautsie/p/3224014.html
Copyright © 2011-2022 走看看