美文网首页
删除链表的倒数第N个节点

删除链表的倒数第N个节点

作者: Haward_ | 来源:发表于2019-10-17 10:58 被阅读0次

思想:利用三根指针

/**
 * 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 pi = head;
        ListNode pj = head;
        ListNode pk = head;
        for(int i=0;i<n;i++) {
            pk = pk.next;
        }
        while(pk!=null) {
            pk = pk.next;
            if(pj!=head) {
                pi = pi.next;
            }
            pj = pj.next;
        }
        if(pi==pj) {
            return head.next;
        }
        pi.next = pj.next;
        return head;
    }
}

相关文章

网友评论

      本文标题:删除链表的倒数第N个节点

      本文链接:https://www.haomeiwen.com/subject/ytcructx.html