首页 > 代码库 > 【Leetcode】Remove Nth Node From End of List
【Leetcode】Remove Nth Node From End of List
Given a linked list, remove the nth 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:
Given n will always be valid.
Try to do this in one pass.
就是先让head走n步,然后再找一个head,让两个head一直走直到走到第一个head走到头,此时第二个head应该刚好走到倒数第n+1个,然后正常删除就好了~唯一的问题就是如果删除的是head,那么单独讨论
package testAndfun; class ListNode{ int val; ListNode next; ListNode(int x){ val = x; next = null; } } public class removeNthFromTheEnd { public static void main(String[] args){ removeNthFromTheEnd rne = new removeNthFromTheEnd(); ListNode x1 = new ListNode(2); ListNode x2 = new ListNode(4); ListNode x3 = new ListNode(3); ListNode x4 = new ListNode(7); ListNode x5 = new ListNode(19); x1.next = x2; x2.next = x3; x3.next = x4; x4.next = x5; prinf(x1); System.out.println(); prinf(rne.removeNthFromEnd(x1, 1)); } public static void prinf(ListNode head){ while(head!=null){ System.out.print(head.val+"->"); head= head.next; } } public ListNode removeNthFromEnd(ListNode head, int n) { ListNode p = head; ListNode lenTmp = head; int len = 0; while(lenTmp!=null){ len++; lenTmp = lenTmp.next; } if(len==n){ head = head.next; return head; } for(int i=0;i<n;i++){ p = p.next; } ListNode pp = head; while(p.next!=null){ p=p.next; pp = pp.next; } ListNode tmp = pp.next.next; pp.next = tmp; return head; } }
【Leetcode】Remove Nth Node From End of List
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。