[算法学习]求链表的中间结点

问题描述: 返回链表的中间结点(如果是两个则返回两个)

解法与分析: 用两个指针移动的方法来解决问题。一个指针每次移动1个结点,另外一个指针移动2个结点。


参考代码如下

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
49
50
51
52
53
54
55
56
57
58
59
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 + "]";
}
}

/**
* 返回中间节点
* @param head
* @return
*/

public static ListNode[] getCenterNode(ListNode head)
{
ListNode[] results = { null, null };
if (head == null)
{
return results;
}
ListNode left = head;
ListNode right = head.next;
// 如果只有一个节点
if (right == null)
{
results[0] = left;
return results;
}
// 如果不止有一个节点
while (right.next != null)
{
left = left.next;
right = right.next;
right = right.next;
if (right == null)
{
results[0] = left;
return results;
}
}
results[0] = left;
results[1] = left.next;
return results;
}