【链表】链表的中间节点

原题 链表的中间节点
给定一个带有头结点 head 的非空单链表,返回链表的中间结点。
如果有两个中间结点,则返回第二个中间结点。

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode middleNode(ListNode head) {
      //由于非空我这边不做边界限制了,然后接下来我们需要理解中间节点的概念,比较笨的方法也是最容易想到的循环遍历头节点然后记录指针数如果最后偶数去中间加1,如果奇数取中间节点就可以了
      int count = 1;
        ListNode currNode = head;
        while(currNode.next != null){
            currNode = currNode.next;
            count++;
        }
        //计数完成/2如果是整数则加1,如果是奇数也是答案加1
        count = (int)Math.floor(count/2)+1;
        while(count > 1){
            head = head.next;
            count--;
        }
        return head;
    }
}
发布了213 篇原创文章 · 获赞 258 · 访问量 28万+

猜你喜欢

转载自blog.csdn.net/wolf_love666/article/details/95211381
今日推荐