标签:
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.
1 /** 2 * Definition for singly-linked list. 3 * public class ListNode { 4 * int val; 5 * ListNode next; 6 * ListNode(int x) { 7 * val = x; 8 * next = null; 9 * } 10 * } 11 */ 12 public class Solution { 13 public ListNode removeNthFromEnd(ListNode head, int n) { 14 if(head==null)return null; 15 ListNode current = head; 16 int length = 0; 17 while(current != null) 18 { 19 current = current.next; 20 length++; 21 } 22 if(n == 1 && length ==1) return null; 23 if(n == length) return head.next; 24 current = head; 25 for(int i = 0 ; i < length - n - 1; i++) 26 { 27 current = current.next; 28 } 29 current.next = current.next.next; 30 return head; 31 32 33 34 } 35 }
另一种思想:看的答案
1 public class Solution { 2 public ListNode removeNthFromEnd(ListNode head, int n) { 3 if(n == 0 || head == null){ 4 return head; 5 } 6 if(n == 1 && head.next==null){ 7 return null; 8 } 9 10 ListNode p = head, q = head; 11 // 让p先行q n个位置 12 for(int i=0; i<n; i++){ 13 if(p != null){ 14 p = p.next; 15 }else{ 16 return head; 17 } 18 } 19 20 // 如果这个时候p已经是null,则说明删除的必定为head 21 if(p == null){ 22 head = head.next; 23 return head; 24 } 25 26 // p和q一起前进 27 while(p.next != null){ 28 q = q.next; 29 p = p.next; 30 } 31 // 删除元素 32 q.next = q.next.next; 33 return head; 34 35 36 } 37 }
Remove Nth Node From End of List
标签:
原文地址:http://www.cnblogs.com/sweetculiji/p/4792850.html