给定一个带有头结点 head 的非空单链表,返回链表的中间结点。
如果有两个中间结点,则返回第二个中间结点。
查找链表的2等分点
快慢指针法
- 时间复杂度:O(N)O(N),其中 NN 是给定列表的结点数目。
- 空间复杂度:O(1)O(1),slow 和 fast 用去的空间。
代码
| 12
 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
 60
 61
 62
 63
 64
 
 |     
 
 
 
 
 
 public static ListNode middleNode(ListNode head) {
 ListNode dummy = new ListNode(0);
 dummy.next = head;
 ListNode q = dummy;
 ListNode s = dummy;
 while (q != null) {
 q = q.next;
 s = s.next;
 if (q == null) {
 break;
 }
 q = q.next;
 }
 return s;
 }
 
 
 
 
 
 
 public static ListNode newSingleLinkedList(int[] vals) {
 ListNode[] nodes;
 nodes = new ListNode[vals.length];
 for (int i = 0; i < vals.length; i++) {
 if (nodes[i] == null) {
 nodes[i] = new ListNode(vals[i]);
 }
 if (i < vals.length - 1) {
 nodes[i + 1] = new ListNode(vals[i + 1]);
 nodes[i].next = nodes[i + 1];
 }
 }
 return nodes[0];
 }
 
 
 
 
 public static class ListNode {
 int val;
 ListNode next;
 
 public ListNode(int val) {
 this.val = val;
 }
 
 public void printNode() {
 ListNode printNode = this;
 StringBuilder sb = new StringBuilder();
 while (printNode != null) {
 sb.append("-->").append(printNode.val);
 printNode = printNode.next;
 }
 System.out.println(sb);
 }
 }
 
 |