问题简介
编程思路
遍历思想
- 由于程序的题意是删除倒数第N个节点,因此我们要定位到该节点进行删除。
- 由于链表是单向的,因此,必须先获取链表的长度,然后通过倒数与整数的关系删除。
- 要关注几个问题:这是边界情况
- 删除第一个元素
- 删除最后一个元素
- 只有一个元素,删除此元素
- 删除中间的元素,要保存当前节点的上一个节点的位置。
以五个元素为例,倒数第一个元素,为正数第5,倒数+整数=长度+1。
双指针思想
代码编写
class ListNode {
int val;
ListNode next;
ListNode() {
}
ListNode(int val) {
this.val = val;
}
ListNode(int val, ListNode next) {
this.val = val;
this.next = next;
}
}
public ListNode removeNthFromEnd(ListNode head, int n) {
int length = sizeOfListNode(head);
if (length == 1 && n == 1) {
return null;
} else if (n == 1) {
// 长度 > 1 并且删除最后一个
return removeLast(head);
} else if (n == length) {
return head.next;
}
// 长度> 1 删除的也不是第一个
int nth = length + 1 - n;
int i = 1;
ListNode node = head;
ListNode pre = null;
while (i<nth) {
pre = node;
node = node.next;
i++;
}
pre.next = node.next;
return head;
}
public ListNode removeLast(ListNode head) {
ListNode node = head;
while (node.next.next!=null) {
node = node.next;
}
node.next = null;
return head;
}
public int sizeOfListNode(ListNode head) {
int length = 0;
ListNode node = head;
while (node != null) {
length++;
node = node.next;
}
return length;
}
总结
这个问题也顺利的解决了,其实这个题目更加简单一些,因为只是涉及遍历,并且在遍历过程中去操作单链表。算是基础能力。
2022年2月11日16:15:28于宋营