每天一到算法题-链表
白话描述:删除链表的倒数第N个节点给定一个链表,删除链表的倒数第 n 个节点,并且返回链表的头结点。说明:给定的 n 保证是有效的。进阶:你能尝试使用一趟扫描实现吗?来源:力扣(LeetCode)链接https://leetcode-cn.com/leetbook/read/top-interview-questions-easy/xn2925/
白话实现:还是只想到了傻瓜解法。
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
int count=1;
ListNode tmp=head;
while(tmp.next!=null){
tmp=tmp.next;
count++;
}
//System.out.println(count);
tmp=head;
if((count==1)&&(n==0)) return head;
else if((count==1)&&(n==1)) return null;
else if(count==n){
head=head.next;return head;
}
else{
for(int i=1;i<count-n;i++){
tmp=tmp.next;
}
tmp.next=tmp.next.next;
return head;
}
}
}