NC53 删除链表的倒数第n个节点
描述
给定一个链表,删除链表的倒数第 nn 个节点并返回链表的头指针
例如,
给出的链表为: 1\to 2\to 3\to 4\to 51→2→3→4→5, n= 2n=2.
删除了链表的倒数第 nn 个节点之后,链表变为1\to 2\to 3\to 51→2→3→5.
备注:
题目保证 nn 一定是有效的
请给出请给出时间复杂度为\ O(n) O(n) 的算法
示例1
输入:
{1,2},2
返回值:
{2}
import java.util.*;
/*
* public class ListNode {
* int val;
* ListNode next = null;
* }
*/
public class Solution {
/**
*
* @param head ListNode类
* @param n int整型
* @return ListNode类
*/
public ListNode removeNthFromEnd (ListNode head, int n) {
// write code here
if(head == null || head.next == null){
return null ;
}
int len = 0 ;
ListNode curt = head ;
while(curt != null){
curt = curt.next ;
len++ ;
}
if(n > len){
return head ;
}
if(n == len){
return head.next ;
}
ListNode fast = head ;
ListNode slow = head ;
while(n > 0){
fast = fast.next ;
n-- ;
}
while(fast.next != null){
fast = fast.next ;
slow = slow.next ;
}
if(slow.next.next == null){
slow.next = null ;
}else{
slow.next = slow.next.next ;
}
return head ;
}
}
本文介绍了一种在O(n)时间复杂度内删除链表倒数第n个节点的方法,通过双指针技巧实现高效定位及删除操作。
257

被折叠的 条评论
为什么被折叠?



