Given A linked list, remove the nth node from the end of the list and return its head.
For example,
n = 2. After removing the second node from the end, the linked list becomes 1->2->3->5.
Note:
Given n would always be valid.
Try to do the in one pass.
Subscribe to see which companies asked this question
Solution 1: Scan the list first, count the total number of elements, and then traverse the list from the beginning until you reach the previous node where you want to delete the node. Because the topic limits the input n is always valid, you do not need to consider that N is greater than the list length or n is less than or equal to 0 of these cases.
/** Definition for singly-linked list. * struct ListNode {* int val; * ListNode *next; * ListNode (int x) : Val (x), Next (NULL) {}}; */classSolution { Public: ListNode* Removenthfromend (listnode* head,intN) {if(head = = NULL)returnNULL; ListNode* p =Head; intnum =0; while(P! =NULL) { ++num; P= p->Next; } if(Num-n = =0) {//The head node is deletedListnode* del =Head; Head= head->Next; Deletedel; } Else{p=Head; for(inti =0; I < num-n-1; ++i) P= p->Next; ListNode* del = p->Next; P->next = p->next->Next; Deletedel; } returnHead; }};
Solution 2: A traversal to solve the problem. Because deleting a node requires changing the next pointer of its previous node, we first find the previous node to delete the node. Set a speed of two pointers, initially pointing to the head node. After the fast pointer moves forward N-Step (note that if the fast pointer reaches the end of the list, which is null, it means that the head node is deleted and needs to be considered separately), two pointers move backwards until the fast pointer is the tail node.
/** Definition for singly-linked list. * struct ListNode {* int val; * ListNode *next; * ListNode (int x) : Val (x), Next (NULL) {}}; */classSolution { Public: ListNode* Removenthfromend (listnode* head,intN) {if(head = = NULL)returnNULL; ListNode* P1 =Head; ListNode* P2 =Head; for(inti =0; I < n; ++i) P1= p1->Next; if(P1 = = NULL) {//The head node is deletedListnode* del =Head; Head= head->Next; Deletedel; returnHead; } while(P1->next! =NULL) {P1= p1->Next; P2= p2->Next; } ListNode* del = p2->Next; P2->next = p2->next->Next; Deletedel; returnHead; }};
[Leetcode]78. Remove Nth node from end of list to delete the last nth node in a linked list