2015年9月18日星期五

Leetcode 19 Remove Nth Node From End of List

Given a linked list, remove the nth node from the end of list and return its head.
For example,
   Given linked list: 1->2->3->4->5, and n = 2.

   After removing the second node from the end, the linked list becomes 1->2->3->5.
Note:
Given n will always be valid.
Try to do this in one pass.
Solution 1: Simple LinkedList question, use dummy node, as may delete head.
 public class Solution {  
   public ListNode removeNthFromEnd(ListNode head, int n) {  
     if (n<=0) return head;  
     ListNode dummy=new ListNode(0);  
     dummy.next=head;  
     ListNode j=dummy;  
     for (int k=0; k<n && j!=null; k++) j=j.next;  
     if (j==null) return head;  
     ListNode i=dummy;  
     while (j.next!=null) {  
       i=i.next;  
       j=j.next;  
     }  
     i.next=i.next.next;  
     return dummy.next;  
   }  
 }  

没有评论:

发表评论