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:
- Direct simulation, first calculate the number of nodes, and then find the node delete
- 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)