给定一个头结点为 head 的非空单链表,返回链表的中间结点。
如果有两个中间结点,则返回第二个中间结点。
暴力解法:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode middleNode(ListNode head) {
int count =1;
List<ListNode> list =new ArrayList();
if(head.next==null){
return head;
}
while(true){
//ListNode head1=head;
//list中存放的引用直接指向堆内存,而并非是指向head,
//所以head引用改变,并不会直接改变List集合中存放的元素。
list.add(head);
if(head.next!=null){
head=head.next;
count++;
continue;
}else{
break;
}
}
if(count%2==0){
return list.get(count/2);
}else{
return list.get(count/2);
}
}
}
快慢指针:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode middleNode(ListNode head) {
//快慢指针解法
ListNode fastHead=head;
ListNode slowHead=head;
if(head.next==null){
return head;
}else if(head.next.next==null){
return head.next;
}
else{
while(true){
slowHead=slowHead.next;
fastHead=fastHead.next.next;
if(fastHead.next!=null&&fastHead.next.next==null){
return slowHead.next;
}else if(fastHead.next==null){
return slowHead;
}
}
}
}
}