题目原意是找一个链表的中间结点,如果中间结点有两个,取靠后的那个
沙雕解法
public class ListNode {
public int val;
public ListNode next;
public ListNode(int val) {
this.val = val;
}
}
给定的是结点数据结构是这样的,因此不能直接用Java里的ArrayList.get(list.size() / 2)这样的方法,我想到的方法就是先遍历一次链表,得到长度,得到中间结点的位置,再迭代,得到中间结点。
public ListNode middleNode(ListNode head) {
if (head == null) {
return null;
}
ListNode tmpListNode = head;
int index = 0, middle;
while (tmpListNode != null) {
index += 1;
tmpListNode = tmpListNode.next;
}
if (index % 2 == 0) {
middle = (int) Math.floor(index / 2);
} else {
middle = index / 2;
}
while (middle > 0) {
head = head.next;
middle--;
}
return head;
}
快慢指针法
先看代码
public ListNode middleNodeTwoPoint(ListNode head) {
if (head == null) {
return null;
}
ListNode slow = head, fast = head;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
}
return slow;
}
slow指针每次往后动一个结点,fast每次往后动两个结点,因此fast走到链表的的末尾时,slow刚好走到链表的中间