https://leetcode.com/problems/remove-nth-node-from-end-of-list/
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.
1 Public classSolution {2 Public StaticListNode Removenthfromend (ListNode head,intN) {3ListNode li=head;4 intLen=0;5 while(li!=NULL){6len++;7Li=Li.next;8 }9 intIndex=len-n+1;Ten if(index==1) {returnHead.next;} OneLi=head; AListNode pre_li=Li; - while(index-->1){ -Pre_li=Li; theLi=Li.next; - } -pre_li.next=Li.next; - returnhead; + } - //Public Static class ListNode { + //int val; A //ListNode Next; at // - //listnode (int x) { - //val = x; - // } - // } - Public Static voidMain (String[]args) { inListnode[]node=NewListnode[4]; - for(inti=0;i<node.length;i++){ tonode[i]=NewListNode (i); + } -Node[0].next=node[1]; theNode[1].next=node[2]; *Node[2].next=node[3]; $ListNode Head=removenthfromend (node[0],2);Panax Notoginseng while(head!=NULL){ - System.out.println (head.val); theHead=Head.next; + } A } the}
Remove Nth Node from End of List