Given a linked list, removeNTh node from the end of list and return its head.
For example,
Given linked list: 1->2->3->4->5, and n = 2. After removing the second node from the end, the linked list becomes 1->2->3->5.
Note:
GivenNWill always be valid.
Try to do this in one pass.
1/** 2 * definition for singly-linked list. 3 * struct listnode {4 * int val; 5 * listnode * Next; 6 * listnode (int x): Val (x), next (null) {} 7 *}; 8 */9 class solution {10 public: 11 listnode * removenthfromend (listnode * head, int N) {12 if (! Head | n <1) return head; // if the head is empty, or N is invalid, 13 listnode node (0); // you can delete 14 nodes by setting the header node. next = head; 15 listnode * pre = & node; // The Slow precursor node 16 listnode * fast = head; 17 while (N & fast) {// point fast to the nth node 18 fast = fast-> next; 19 -- N; 20} 21 if (N &&! Fast) return head; // if the length of the linked list is not greater than N, 22 listnode * slow = head; 23 while (FAST) {// fast and slow move at the same time, when slow is null, end 24 fast = fast-> next; 25 pre = slow; 26 slow = slow-> next; 27} 28 pre-> next = slow-> next; // Delete the nth node 29 delete slow; 30 return node. next; 31} 32 };
Set up the first and second pointers. Assume that the first pointer is fast and the last pointer is slow. First, let the fast pointer point to head, and then take n steps backward to point to the nth node. Then, the slow Pointer Points to head, let the fast pointer and the slow pointer move back at the same time, knowing that slow is null, then the fast Pointer Points to the last n nodes
Remove nth node from end of list