876. Middle of the Linked List
描述
Given a non-empty, singly linked list with head node head, return a middle node of linked list.
if there are two middle nodes, return the second middle node.
- Example 1:
Input: [1,2,3,4,5]
Output: Node 3 from this list (Serialization: [3,4,5])
The returned node has value 3. (The judge’s serialization of this node is [3,4,5]).
Note that we returned a ListNode object ans, such that:
ans.val = 3, ans.next.val = 4, ans.next.next.val = 5, and ans.next.next.next = NULL. - Example 2:
Input: [1,2,3,4,5]
Output: Node 3 from this list (Serialization: [3,4,5])
The returned node has value 3. (The judge’s serialization of this node is [3,4,5]).
Note that we returned a ListNode object ans, such that:
ans.val = 3, ans.next.val = 4, ans.next.next.val = 5, and ans.next.next.next = NULL.
代码一
class Solution { public ListNode middleNode(ListNode head) { ListNode node=head; int i=0; while(node!=null) { i++; node=node.next; } int loc=i/2+1; i=1; ListNode node1=head; while(i<loc) { node1=node1.next; i++; } return node1; } }
代码二
public ListNode middleNode(ListNode head) { ListNode listNode = new ListNode(0); ListNode fast=head; ListNode low=head; while(fast!=null&&fast.next!=null) { fast=fast.next.next; low=low.next; } return low.next; }
代码三
class Solution { public ListNode middleNode(ListNode head) { ListNode fast=head; ListNode low=head; //对比2方法,假装自己先跑了两步 if(fast!=null&&fast.next!=null){ fast=fast.next.next; }else{ return low; } while(fast!=null&&fast.next!=null) { fast=fast.next.next; low=low.next; } return low.next; } }
代码四
public ListNode middleNode(ListNode head) { ListNode fast=head; ListNode low=head; //对比2方法,假装自己先跑了两步 if(head==null&&head.next==null) return head; while(fast!=null&&fast.next!=null) { fast=fast.next.next; low=low.next; } return low; }
近期评论