My crappy code with real one pass [java]


  • 0
    Y

    I think the only way to do it in one pass is to store the last n elements visited.

    /**

    • 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) {
      if(head==null||head.next ==null )
      return null;

       ListNode[] nodes=new ListNode[n];
       int cur=0;
       ListNode tmp=head;
       while(tmp.next!=null){
           nodes[cur]=tmp;
           cur=(cur+1)%n;
           tmp=tmp.next;
       }
       if(n==1)
       {
           nodes[(cur+n-1)%n].next=null;
           return head;
       }
       ListNode todel=nodes[(cur+2*n+1)%n];
       if(todel==head){
           return head.next;
       }
       ListNode prev=nodes[(cur)%n];
       prev.next=prev.next.next;
       return head;
      

      }
      }


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.