链表中点取值

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



全部评论

相关推荐

不愿透露姓名的神秘牛友
02-12 10:05
小米集团 算法工程师 28.0k*15.0
泡沫灬一触即破:楼上那个看来是看人拿高薪,自己又不如意搁这泄愤呢是吧,看你过往评论很难不怀疑你的精神状态
点赞 评论 收藏
分享
2024-12-26 13:00
太原理工大学 Java
会飞的猿:简历没啥大问题啊,感觉是缺少了实习经历。多投投先找个中小厂过渡一下吧
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务