19. 删除链表的倒数第N个节点
给定一个链表,删除链表的倒数第 n 个节点,并且返回链表的头结点。
示例:
给定一个链表: 1->2->3->4->5, 和 n = 2.
当删除了倒数第二个节点后,链表变为 1->2->3->5.
代码写的太弱智,不想分析了,写点注释好了。大佬勿喷。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
int size = 1; // 计算长度
ListNode temp = head;
while (true&&temp!=null) {
if (temp.next == null) {
break;
}
size++;
temp = temp.next;
}
if (size<=1) { //排除空或者长度为1的链表
return null;
}
if (n==size) {
return head.next;
}
ListNode result = head; // 保存结果
for (int i = 0; true; i++) {
//删除第N个元素,即操作第N-1个元素
if (i == size-n-1 ){
if (head.next == null || head == null) {
head = null;
} else {
head.next=head.next.next;
}
break;
}
head = head.next;
}
return result;
}
}