Topic:
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.
Ideas:
- Count the number of nodes first, and change the number of count-n number of next to count-n-2.
- The topic requires the best to traverse, that is mathematically clever, two pointers, first to go N steps, and then start and second at the same time, until the next is empty, then the second next to next
public class Removenthfromend {public class ListNode {int val; ListNode Next; ListNode (int x) {val = x; next = null;}} /*//first count the number of nodes count, the number of count-n number of the next change to the number of count-n-2 public ListNode removenthfromend (listnode head, int n) {int count = 1; ListNode temp = Head;while (Temp.next! = null) {count++;temp = Temp.next;} int i = count-n;if (i = = 0) {return head.next;} temp = Head;while (i > 1) {temp = temp.next;i--;} Temp.next = Temp.next.next;return head; } *///the topic requires the best to traverse, that is, mathematically clever, two pointers, first to go n steps,//and second at the same time walk, until the first next is empty, the second next change to next Nextpublic ListNode Removenthfromend (listnode head, int n) {ListNode first = head, second = head;for (int i=n; i>0; i--) {first = he Ad.next;} if (first = = null) {return first;} while (first.next! = null) {first = First.next;second = Second.next;} Second.next = Second.next.next;return head; }}
Leetcode | #19 Remove Nth Node from End of List