[Leetcode] 019. Remove Nth Node from End of List (Easy) (C++/python)

Source: Internet
Author: User

Index: [Leetcode] leetcode key index (C++/JAVA/PYTHON/SQL)
Github:https://github.com/illuz/leetcode

019.remove_nth_node_from_end_of_list (Easy) links

Title: https://oj.leetcode.com/problems/remove-nth-node-from-end-of-list/
Code (GitHub): Https://github.com/illuz/leetcode

Test Instructions

Deletes the reciprocal nth node of a one-way linked list.

Analysis
    1. Direct simulation, first calculate the number of nodes, and then find the node delete
    2. With two pointers, one goes first N steps, and then goes together.

Here in C + + implementation of the first, with Python implementation of the second.
Java words and C++/python almost, do not write out.

Code

C++:

Class Solution {public:    listnode *removenthfromend (listnode *head, int n) {if (n = = 0) return head;//count the node Nu Mberint num = 0; ListNode *cur = head;while (cur! = NULL) {cur = cur->next;num++;} if (num = = N) {//Remove first Nodelistnode *ret = Head->next;delete head;return ret;} else {//remove (cnt-n) th Nodein T m = num-n-1;cur = Head;while (m--) cur = cur->next; ListNode *rem = Cur->next;cur->next = Cur->next->next;delete rem;return head;}}    ;


Python:

Class solution:    # @return a listnode    def removenthfromend (self, head, N):        dummy = listnode (0)        Dummy.next = head        p, q = dummy, dummy                # first ' Q ' Go n step for        I in range (n):            q = q.next        # Q & p< C9/>while q.next:            p = p.next            q = q.next        rec = p.next        p.next = rec.next        del rec        return dummy . Next


[Leetcode] 019. Remove Nth Node from End of List (Easy) (C++/python)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.