首页 > 代码库 > Remove Nth Node From End of List

Remove Nth Node From End of List

需要额外添加两个相距为n的节点,遍历一遍之后就可以得到结果。

/** * Definition for singly-linked list. * public class ListNode { *     int val; *     ListNode next; *     ListNode(int x) { *         val = x; *         next = null; *     } * } */public class Solution {    public ListNode removeNthFromEnd(ListNode head, int n) {        ListNode p=head;        ListNode ne=head;        int i=0;        while(ne.next!=null){            ne=ne.next;            if(i>=n){                p=p.next;            }            i++;        }        if(i==0){            return null;        }        else if(i+1==n){            return head.next;        }        else{            p.next=p.next.next;            return head;        }    }}

 

Remove Nth Node From End of List