从单链表中删除倒数第N个节点,要求之遍历一遍链表。
例子如下:
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.
Java版本,
/**
* 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) {
if(null == head || n <= 0) return head;
ListNode myhead = head, tail = head;
while(n > 0 && tail.next != null){
tail = tail.next;
n--;
}
if(n > 1) return head;//n > sizeOfList
if(n == 1 && tail.next == null) return head.next;
while(tail.next != null ){
myhead = myhead.next;
tail = tail.next;
}
myhead.next = myhead.next.next;
return head;
}
}