题目
给你单链表的头结点 head ,请你找出并返回链表的中间结点。
如果有两个中间结点,则返回第二个中间结点。
示例 1:
输入:head = [1,2,3,4,5]
输出:[3,4,5]
解释:链表只有一个中间结点,值为 3 。
分析
用快慢指针即可,在快指针遍历完以后慢指针指向的就是目标结点
public class LinkNode {int val;LinkNode next;public LinkNode(int data) {this.val = data;this.next = null;}
}
public class LinkList {LinkNode head;public LinkList() {this.head = null;}public LinkNode getHead() {return this.head;}//添加元素public void addNode(int data) {LinkNode node = new LinkNode(data);if (this.head == null) {this.head = node;} else {LinkNode cur = this.head;while(cur.next != null) {cur = cur.next;}cur.next = node;}}//正序打印public void print(LinkNode node) {while(node != null) {System.out.print(node.val);System.out.print(" ");node = node.next;}System.out.println();}public LinkNode getMiddle() {if(this.head == null || this.head.next == null) {return this.head;}LinkNode slow = this.head;LinkNode fast = this.head;while(fast != null && fast.next != null) {slow = slow.next;fast = fast.next.next;}return slow;}
}
public class middleoftheLinkedList {public static void main(String[] args) {LinkList list = new LinkList();list.addNode(1);list.addNode(2);list.addNode(3);list.addNode(4);list.addNode(5);System.out.println(list.getMiddle().val);list = new LinkList();list.addNode(1);list.addNode(2);list.addNode(3);list.addNode(4);list.addNode(5);list.addNode(6);System.out.println(list.getMiddle().val);}
}