1. Given a linked list, delete the nth node in the list and return the head node of the linked list.
Give the list 1->2->3->4->5->null and n = 2.
After you delete the second-to-last node, the list becomes 1->2->3->5->null.
Note
The number of nodes in the list is greater than or equal to n
challenges
O (n) Time complexity
Problem-solving ideas: Just beginning to see the last nth node, can not help feeling if it is an array to directly upside down. But for the linked list, be sure to think of the most common method---fast and slow pointer. Set a fast and slow pointer, a fast pointer to the N-step, then the speed of the pointer to go together, when the fast==null, the slow pointer is the value of the bottom nth, and then delete the line.
1 /**2 * Definition for ListNode.3 * public class ListNode {4 * int val;5 * ListNode Next;6 * ListNode (int val) {7 * This.val = val;8 * this.next = null;9 * }Ten * } One */ A Public classSolution { - /** - * @paramhead:the first node of linked list. the * @paramn:an Integer. - * @return: The head of linked list. - */ -ListNode Removenthfromend (ListNode head,intN) { + //Write your code here -ListNode fast=head; +ListNode result =NewListNode (0); AResult.next =head; at for(inti=0;i<n-1;i++){ -Fast =Fast.next; - } -ListNode now =result; - while(Fast.next! =NULL){ -Fast =Fast.next; innow =Now.next; - } toNow.next =Now.next.next; + returnResult.next; - } the}
Delete the nth node in the linked list