题目链接:Remove Nth Node From End of List
这道题的意思是从链表的尾部开始查找,删除第n个节点。
最普通的方法就是遍历两次,第一次遍历计算出链表的长度为len,那么倒数第n个节点,即为正数第len-n+1个,第二次遍历删除对应节点即可。
本以为这样的做法不过AC,但是竟然通过了。
解法一:
/**
* 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) {
if(head==null)
return head;
ListNode index = new ListNode(0);
index.next = head;
int len = 1;
while(head.next!=null){
len++;
head = head.next;
}
int tmp = len-n+1;
head = index.next;
if(tmp == 1){
head = head.next;
return head;
}
while(tmp>2){
head = head.next;
tmp--;
}
head.next = head.next.next;
return index.next;
}
}
解法二:只需要遍历一次,使用双指针的方法,faster和slower,初始状态faster和slower均指向head节点,首先faster向前走n步,因为n始终为有效的即其不会超过链表的长度,如果此时faster==null,则说明n==len,即删除倒数第len个节点也就是正数第一个节点,那么返回head.next即可。
如果faster!=null,那么接下来faster和slower同时向前走,直到faster走到链表的尾部,而此时slower指向的即为将要删除的节点的前一个节点。
代码如下:
/**
* 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) {
if(head==null||head.next==null)
return null;
ListNode faster = head;
ListNode slower = head;
int i = 0;
while(i<n){
faster = faster.next;
i++;
}
if(faster==null)
return head.next;
while(faster.next!=null){
slower = slower.next;
faster = faster.next;
}
slower.next = slower.next.next;
return head;
}
}