您的位置:首页 > 其它

166 - 链表倒数第n个节点

2017-04-20 09:08 239 查看
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;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: