Leetcode 19. Remove Nth Node From End of List JAVA语言
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Leetcode 19. Remove Nth Node From End of List JAVA语言相关的知识,希望对你有一定的参考价值。
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.
题意:删除倒数第N个节点。尽量一次遍历。
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ public class Solution { public ListNode removeNthFromEnd(ListNode head, int n) { if(head==null || n<1)return head; ListNode cur=head; while(cur!=null){ n--; cur=cur.next; } if(n==0)head=head.next; if(n<0){ cur=head; while(++n!=0){ cur=cur.next; } cur.next=cur.next.next; } return head; } }
PS:左老师提供的一种找倒数第K个的思路。先遍历一遍,同时K--,最后判断K的大小。K==0说明要删除的是头结点。K>0,说明K不对。K<0的时候,再从头走一遍,不过此时K++,K=0的时候也就找到了第K-1个。此时直接删除就行。
【方法2】网上的快慢指针法。fast先走K-1步。然后slow和fast同时一步一步走。fast到尾部时slow正好到达倒数第K-1个。
/* public class ListNode { int val; ListNode next = null; ListNode(int val) { this.val = val; } }*/ public class Solution { public ListNode FindKthToTail(ListNode head,int k) { if(head==null || k==0)return null; ListNode fast=head; for(int i=0;i<k-1;i++){ ////防止K无效 if(fast.next!=null){ fast=fast.next; }else{ return null; } } ListNode slow=head; while(fast.next!=null){ slow=slow.next; fast=fast.next; } return slow; } }
以上是关于Leetcode 19. Remove Nth Node From End of List JAVA语言的主要内容,如果未能解决你的问题,请参考以下文章
leetcode19. Remove Nth Node From End of List
LeetCode 19. Remove Nth Node From End of List
LeetCode-19-Remove Nth Node From End of List
leetcode 之Remove Nth Node From End of List(19)