Given A linked list, remove the nth node from the end of the list and return its head.
For example,
1->2->3->4->5 N = 2. 1->2->3->5.
Note:
Given n would always be valid.
Try to do the in one pass.
Problem-Solving ideas: 1. Using a double pointer, first let the fast pointer jump N nodes, and then the two pointers together backward until the fast pointer is null, when the slow pointer points to the node is the desired node
2. Using the principle of hashing, the nodes exist in order vector, using the vector index to find the node.
#include <iostream> #include <vector>using namespace std;//definition for singly-linked list.struct listnode {int val; ListNode *next; ListNode (int x): Val (x), Next (NULL) {}};//solution one: double pointer listnode *removenthfromend (listnode *head, int n) {Listnode*fastn_node = head;for (int i = 0; I! = N; ++i) Fastn_node = fastn_node->next; Listnode*slown_node = head; Listnode*preslown_node = Slown_node;while (fastn_node!=null) {preslown_node = Slown_node; Fastn_node = fastn_node->next; Slown_node = Slown_node->next;} if (Slown_node = = head) head = Head->next;elsepreslown_node->next = Slown_node->next;return head;} Solution Two: Hash listnode *removenthfromend (listnode *head, int n) {vector<listnode*>nodelistvector; listnode* Tmphead = Head;int totalnum = 0;for (; Tmphead! = NULL; Tmphead=tmphead->next,++totalnum) Nodelistvector.push_back (tmphead); if (Totalnum-n-1 < 0) head = head->next; Elsenodelistvector[totalnum-n-1]->next = Nodelistvector[totalnum-n]->next;returnHead;}
Remove Nth Node from End of List