链表中点取值

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



全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务