链表中点取值

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



全部评论

相关推荐

01-29 15:45
已编辑
华中科技大学 前端工程师
COLORSN:可以试一下,小厂看技术栈是不是很落后,如果太拉胯就别去,个人认为有实习氛围比你自己琢磨要高效不少,然后就是小厂其实也有可能会问的很难,这都比较难说,还是看自己项目含金量够不够,寒假还能不能推进学习再选择,毕竟去实习过年就10天假了
点赞 评论 收藏
分享
ros275229:社团删了吧,cf因该1200才勉强入门吧,也删了,你可以写算法刷了多少道,都比这个好
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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