题目:
876. 链表的中间结点
题解:快慢指针
解释一: 解释二: 解释三:
1. 在两个中间结点的时候,返回第二个中间结点:
public static ListNode
middleNode(ListNode head
) {
if(head
== null
)
{
return null
;
}
ListNode slow
= head
;
ListNode fast
= head
;
while(fast
!= null
&& fast
.next
!= null
)
{
slow
= slow
.next
;
fast
= fast
.next
.next
;
}
return slow
;
}
2. 在两个中间结点的时候,返回第一个中间结点:
public static ListNode
middleNode(ListNode head
) {
if(head
== null
)
{
return null
;
}
ListNode slow
= head
;
ListNode fast
= head
;
while(fast
.next
!= null
&& fast
.next
.next
!= null
)
{
slow
= slow
.next
;
fast
= fast
.next
.next
;
}
return slow
;
}
代码:快慢指针
public class code876 {
public static ListNode
middleNode(ListNode head
) {
if(head
== null
)
{
return null
;
}
ListNode slow
= head
;
ListNode fast
= head
;
while(fast
!= null
&& fast
.next
!= null
)
{
slow
= slow
.next
;
fast
= fast
.next
.next
;
}
return slow
;
}
private static ListNode
createLinkedList(int[] arr
) {
if (arr
.length
== 0) {
return null
;
}
ListNode head
= new ListNode(arr
[0]);
ListNode current
= head
;
for (int i
= 1; i
< arr
.length
; i
++) {
current
.next
= new ListNode(arr
[i
]);
current
= current
.next
;
}
return head
;
}
private static void printLinkedList(ListNode head
) {
ListNode current
= head
;
while (current
!= null
) {
System
.out
.printf("%d -> ", current
.val
);
current
= current
.next
;
}
System
.out
.println("NULL");
}
public static void main(String
[] args
) {
int[] x
= { 1, 2, 3, 4, 5, 6 };
ListNode list
= createLinkedList(x
);
printLinkedList(list
);
ListNode res
= middleNode(list
);
System
.out
.println(res
.val
);
}
}
参考:
链表的中间结点快慢指针(注意链表长度为偶数时,返回第 2 个结点的细节)C++ 图解证明快慢指针 上次鹅场面试还遇到过 :)典型的快慢指针题目
转载请注明原文地址:https://ipadbbs.8miu.com/read-3191.html