4.20
这种删除倒数第几个节点的题目,已经做过好多了呢。
/**
* Definition for ListNode.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int val) {
* this.val = val;
* this.next = null;
* }
* }
*/
public class Solution {
/**
* @param head: The first node of linked list.
* @param n: An integer.
* @return: Nth to last node of a singly linked list.
*/
ListNode nthToLast(ListNode head, int n) {
// write your code here
if(head == null){
return head;
}
ListNode tmp = head;
for(int i = 1; i < n; i++){
tmp = tmp.next;
}
ListNode flag = head;
while(tmp.next != null){
flag = flag.next;
tmp = tmp.next;
}
return flag;
}
}