leetcode--Remove Nth Node From End of List

来源:互联网 发布:韩孝珠李钟硕 知乎 编辑:程序博客网 时间:2024/06/17 19:52

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.

[java] view plain copy
  1. /** 
  2.  * Definition for singly-linked list. 
  3.  * public class ListNode { 
  4.  *     int val; 
  5.  *     ListNode next; 
  6.  *     ListNode(int x) { val = x; } 
  7.  * } 
  8.  */  
  9. public class Solution {  
  10.     public ListNode removeNthFromEnd(ListNode head, int n) {  
  11.         ListNode p = head;  
  12.         while(n>0 && p!=null){  
  13.             p = p.next;  
  14.             n--;  
  15.         }  
  16.                   
  17.         ListNode newHead = new ListNode(1);  
  18.         newHead.next = head;  
  19.         ListNode q = newHead;         
  20.         while(p!=null){  
  21.             q = q.next;  
  22.             p = p.next;  
  23.         }      
  24.          
  25.         q.next = q.next.next;  
  26.         return newHead.next;  
  27.     }  
  28. }  

原文链接http://blog.csdn.net/crazy__chen/article/details/45566815

原创粉丝点击