[算法学习]求出链表中倒数第n个节点

问题描述: 求出链表中倒数第n个节点。例如:1,2,3,4,5,倒数第2个是4

解法与分析: 用两个指针的方法。

  1. 第一个指针起始位置在0位置,第二个指针起始位置在n-1位置。
  2. 两个指针同时移动,每次移动1个结点。
  3. 当第二个指针移动到最后一个节点时,第一个指针所指结点就是倒数第n个结点。

参考代码如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
static class ListNode
{

int val;
ListNode next;

public ListNode(int val)
{

this.val = val;
}

public ListNode(int val, ListNode next)
{

this.val = val;
this.next = next;
}

@Override
public String toString()
{

return "ListNode [val=" + val + "]";
}
}

public static ListNode getLastNode(ListNode head, int n)
{

if (head == null || n <= 0)
{
return null;
}

ListNode left = head;
ListNode right = head;

for (int i = 1; i < n; i++)
{
right = right.next;
if (right == null)
{
return null;
}
}
while (right.next != null)
{
left = left.next;
right = right.next;
}
return left;
}