您的位置:首页 > 编程语言 > Java开发

java链表寻找中间节点

2017-10-15 13:06 190 查看
public class ListNode {

public int info;
public ListNode next;//这里就是链接,指向下一个节点的内存地址
ListNode first, last, newNode;

public ListNode buildList(int[] input) {
if (input.length > 0) {
for (int i = 0; i < input.length; i++) {
newNode = new ListNode();
newNode.info = input[i];
newNode.next = null;
if (first == null) {
first = newNode;
last = newNode;
} else {
last.next = newNode;
last = newNode;
}
}
}
return first;
}

public static void main(String[] args) {
int[] array = {1, 2, 3, 4};
ListNode linkedList = new ListNode();
ListNode head = linkedList.buildList(array);
ListNode.printList(head);
findMid(head);
}

private static void printList(ListNode head) {

while (head != null) {
System.out.println(head.info);
head = head.next;
}
}

private static void findMid(ListNode head) {
ListNode slow = head;
ListNode fast = head;

while (fast !=null && fast.next !=null )
{
fast = fast.next.next;
slow = slow.next;
}//这个总数是4,会取3
//这个方法也可以
//        while(fast.next != null){
//            if(fast.next.next != null){
//                fast = fast.next.next;
//                slow = slow.next;
//            } else {
////                fast = fast.next;
//                break;//这个地方就退出循环了,用break或者fast = fast.next;都可以
//            }
//
//        }
System.out.println(slow.info);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: