1 题目理解
我昨天又忘了更新了。。~~(>_<)~~ 先补
这道题就是说,删除链表的倒数第N个节点。。
链表本身是不知道有多少个元素的。。不过这种题都一个解法
设置Faster和slower两个指针,faster指针比slower先走k-1步。。然后再一起移动。。这样faster到头时,slower也指向了倒数第k个了~~~
然后就标准的移除了。。很简单。。不多说,取快递去了
2 原题
Remove Nth Node From End of List
Given a linked list, remove the nth node from the end of list and return its head.
For example,
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.
Note:
Given n will always be valid.
Try to do this in one pass.
Subscribe to see which companies asked this question
3 AC解
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
/**
* 本质上,倒数第n个,只需要设置两个指针,一个走得快,一个走得慢
* 走得快的比走的慢的多走n步就可以,当走的快的到了尾巴,那么也到了倒数第n个的位置了
*
* 这题只需要注意初始的边界调节,比如只有一个且删除第一个怎么办,我是采用多创建了指针,指在头结点之前就好
* */
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode faster=head,slower;
ListNode prehead=new ListNode(0);
prehead.next=head;
slower=prehead;
//首先多走n步
for(int i=0;i<n;i++){
faster=faster.next;
}
while(faster!=null){
faster=faster.next;
slower=slower.next;
}
//删除slower
slower.next=slower.next.next;
return prehead.next;
}
}