Remove Nth Node From End of List

来源:互联网 发布:工程宝软件下载 编辑:程序博客网 时间:2024/04/30 09:27
/** * 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) {        // Start typing your Java solution below        // DO NOT write main() function        if(head.next==null)return null;                ListNode last = head;        for(int i = 0; i<n;i++){            last = last.next;        }        if(last==null)return head.next;        ListNode now = head;        while(last.next!=null){            last = last.next;            now = now.next;        }        now.next = now.next.next;        return head;    }}