找到单链表倒数第 n 个节点,保证链表中节点的最少数量为 n 。
给出链表 3->2->1->5->null
和 n = 2
,返回倒数第二个节点的值 1
一个简单的思路就是先将链表进行反转,然后在反转后的链表中,顺着找第 n 个元素即可。
/**
* 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) {
ListNode node = null;
while (head != null) {
ListNode temp = head.next;
head.next = node;
node = head;
head = temp;
}
for (int i = 1; i < n; i++) {
node = node.next;
}
return node;
}
}
考虑一下思路1会出现的问题:当链表很长时,效率会大大降低。例如对于 100 个元素的链表,查找倒数第 100 个,那么就等于将链表遍历了 2 次,效率很低。
改进思路:
/**
* 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) {
if (head == null || n < 1) {
return null;
}
ListNode p1 = head;
ListNode p2 = head;
for (int j = 0; j < n - 1; ++j) {
if (p2 == null) {
return null;
}
p2 = p2.next;
}
while (p2.next != null) {
p1 = p1.next;
p2 = p2.next;
}
return p1;
}
}
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有