链表中点取值

其实很好弄,条件是fast.next!=null,fast.next.next!=null
画四个点,把两个指针的位置画一下根据条件判断slow的落点就行了
1、偶数上中点,基数中点
public static Node midOrUpMidNode(Node head) {
   if (head == null || head.next == null || head.next.next == null) {
      return head;
   }
   // 链表有3个点或以上
   Node slow = head.next;
   Node fast = head.next.next;
   while (fast.next != null && fast.next.next != null) {
      slow = slow.next;
      fast = fast.next.next;
   }
   return slow;
}

2、偶数下中点,基数中点
public static Node midOrDownMidNode(Node head) {
   if (head == null || head.next == null) {
      return head;
   }
   Node slow = head.next;
   Node fast = head.next;
   while (fast.next != null && fast.next.next != null) {
      slow = slow.next;
      fast = fast.next.next;
   }
   return slow;
}

3、偶数上中点前一个,基数中点前一个
public static Node midOrUpMidPreNode(Node head) {
   if (head == null || head.next == null || head.next.next == null) {
      return null;
   }
   Node slow = head;
   Node fast = head.next.next;
   while (fast.next != null && fast.next.next != null) {
      slow = slow.next;
      fast = fast.next.next;
   }
   return slow;
}

4、偶数下中点前一个,基数中点前一个(允许存在两位,那么就是头节点)
public static Node midOrDownMidPreNode(Node head) {
   if (head == null || head.next == null) {
      return null;
   }
   if (head.next.next == null) {
      return head;
   }
   Node slow = head;
   Node fast = head.next;
   while (fast.next != null && fast.next.next != null) {
      slow = slow.next;
      fast = fast.next.next;
   }
   return slow;
}



全部评论

相关推荐

“校招”、“3-5年经验”
飞花断音:小公司招逆向的不要去,基本上都是搞黑灰产违法的东西
点赞 评论 收藏
分享
05-09 12:23
已编辑
华南理工大学 Java
野猪不是猪🐗:给他装的,双九+有实习的能看的上这种厂我直接吃⑨✌们拿它练练面试愣是给他整出幻觉了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务