LeetCode之19. 删除链表的倒数第N个节点

19. 删除链表的倒数第N个节点(https://leetcode-cn.com/probl...

给定一个链表,删除链表的倒数第 _n _个节点,而且返回链表的头结点。
示例:
给定一个链表: 1->2->3->4->5, 和 n = 2.
当删除了倒数第二个节点后,链表变为 1->2->3->5.node

/**
 * 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;
    }
}
相关文章
相关标签/搜索