题目类型
链表
题意:
给出一个链表和一个数字n移除链表中从后往前的第n个节点,输出新的链表。
例子:
Given linked list: 1->2->3->4->5, and n = 2.
After removing the second node from the end, the linked list becomes 1->2->3->5.
我的思路:
65%
- 先计算出链表的节点个数m,从后往前的第n个即为:从前往后的m - n + 1
- 从前往后找到第m-n+1个节点为待删除节点, 将其前面节点的next指针更新为后一个节点,OK
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode extra = new ListNode(0);//额外节点,防止head节点改变导致找不到原来的头
extra.next = head;
int count = 0;
while (head != null) {
count++;
head = head.next;
}
int location = count - n + 1;
head = extra.next;
ListNode pre = null;
for(int i = 1; i < location; i++){
pre = head;
head = head.next;
}
if (pre == null) {
extra.next = extra.next.next;
}
else pre.next = head.next;
return extra.next;
}
}
方法二:找待删除节点的新方法
beat 99%
待待删除节点到尾部的距离为n,可以设置一个slow,fast指针,初始为head,fast先从前往后移动n个位置,然后fast从当前位置移动到末尾的同时移动slow,那么fast到末尾时slow恰好到该删除的节点的上一个。
- 注意:边界情况的判断
- 若head为null,return null
- 若删除为第一个节点
- 若n大于链表长度
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
if(head == null) return null;
ListNode copy = head;
ListNode copy2 = head;
while(n-- > 0){
if(head.next == null){
if(n == 0) return copy.next;//删除的为第一个节点
else return null;//n大于链表长度
}
head = head.next;
}
while(head.next != null){
head = head.next;
copy2 = copy2.next;
}
copy2.next = copy2.next.next;
return copy;
}
}