链表中点取值

其实很好弄,条件是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;
}



全部评论

相关推荐

不愿透露姓名的神秘牛友
07-03 18:22
投了几百份简历,专业和方向完全对口,都已读不回。尝试改了一下学校,果然有奇效。
steelhead:这不是很正常嘛,BOSS好的是即便是你学院本可能都会和聊几句,牛客上学院本机会很少了
点赞 评论 收藏
分享
湫湫湫不会java:先投着吧,大概率找不到实习,没实习的时候再加个项目,然后把个人评价和荣誉奖项删了,赶紧成为八股战神吧,没实习没学历,秋招机会估计不多,把握机会。或者说秋招时间去冲实习,春招冲offer,但是压力会比较大
点赞 评论 收藏
分享
代码飞升:别用口语,后端就写后端,前端就写前端,最后别光后悔
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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