题目
稍微分析一下题目
题目算是比较简单的了
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
int length=0;
ListNode temp=head;
while(temp!=null){
temp=temp.next;
length++;
}
temp=head;
length=length-n;
//当n=length时,将删除第一个数,所以直接返回第一个节点的next即可
if(length==0) return head.next;
int i=0;
while(i<length-1){
temp=temp.next;
i++;
}
temp.next=temp.next.next;
return head;
}
}
我的方法算是遍历了两遍
那么有没有只用遍历一遍的算法呢?
public ListNode removeNthFromEnd(ListNode head, int n) {
//定义一个哑节点,方便排除特殊情况
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode first = dummy;
ListNode second = dummy;
// 让两个临时节点相距n+1个字符
for (int i = 1; i <= n + 1; i++) {
first = first.next;
}
// 将第一个节点移到末尾,第二个节点始终和第一个节点保持n+1的距离
while (first != null) {
first = first.next;
second = second.next;
}
second.next = second.next.next;
return dummy.next;
}