删除倒数第n个词

来源:互联网 发布:热聊营销软件 编辑:程序博客网 时间:2024/06/17 00:39
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode p = head;
        ListNode q = new ListNode(-1);
        ListNode ans = q;
        q.next = head;
        
        int i = 0;
        while(i<n-1){
            p = p.next;
            i++;
        }
        while(p.next!=null){
            q = q.next;
            p = p.next;
        }   // p==end,
        
        q.next = q.next.next;
        return ans.next;
    }
}
0 0
原创粉丝点击