题目描述:
给定一个链表,删除链表的倒数第 nnn 个节点并返回链表的头指针例如,
给出的链表为: 1→2→3→4→51\to 2\to 3\to 4\to 51→2→3→4→5, n=2n= 2n=2.
删除了链表的倒数第 nnn 个节点之后,链表变为1→2→3→51\to 2\to 3\to 51→2→3→5.题目保证 nnn 一定是有效的
请给出请给出时间复杂度为 O(n) 的算法
题目分析:
时间复杂度为O(n),所以循环只能单层
先计算链表长度,然后计算需要删除的节点,进行删除
java代码实现:
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){//判空
return null;
}
ListNode a = head;
int count = 0;
while(a != null){//计算链表长度
count += 1;
a = a.next;
}
if(count == n){//若为删除第一个,则直接从第二个开始返回
return head.next;
}
count = count - n;
int j = 0;
a = head;
for(j = 1;j < count;j++){
a = a.next;
}
if(a.next.next == null){//判断是否为最后一个
a.next = null;
}else{
a.next = a.next.next;
}
return head;
}
}