Remove Nth Node from End of List

来源:互联网 发布:ai软件作品 编辑:程序博客网 时间:2024/04/30 15:21
/** * 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() functionif(head == null)return null;int i = 0;ListNode tail = head;ListNode node = head;while(i++ < n){tail = tail.next;}if(tail == null)return head.next;while(tail.next != null){tail = tail.next;node = node.next;}node.next = node.next.next;return head;}}