19. 删除链表的倒数第N个节点(https://leetcode-cn.com/probl...
给定一个链表,删除链表的倒数第 _n _个节点,并且返回链表的头结点。
示例:
给定一个链表: 1->2->3->4->5, 和 n = 2.
当删除了倒数第二个节点后,链表变为 1->2->3->5.
/**
* 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) {
//要删除的节点
ListNode temp=head;
//找到要删除的节点判断条件
ListNode cur=head;
//要删除节点的前置节点
ListNode pre=null;
//记录什么时候双节点开始同时移动
int pos=1;
while(cur.next!=null){
//当n比cur节点的位置坐标小时(从1开始计数),要删除的节点指针开始移动。等cur节点的下个节点为空时,指针2刚好找到删除节点。
if(pos>=n){
pre=temp;
temp=temp.next;
}
pos++;
cur=cur.next;
}
if(pre==null){
//当删除的是第一个节点时,直接返回第二个节点即可
return head.next;
}
//否则删除temp节点
pre.next=temp.next;
return head;
}
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。