算法——找单链表中点

超级简单,做个记录。

设两个指针,一个每次走两步,一个每次走一步,到头了就是中点。

类似与找单链表倒数第几个元素这样到算法。

实现如下:

package com.song.algorithm;

public class FindMid {
	public static class Node{
		Node next;
		String data;
		public Node(String data){
			this.data = data;
		}
	}
	
	public static Node findMiddle(Node start){
		Node prev;
		if(start == null ){
			return null;
		}else{
			if(start.next != null) {
				prev = start.next;
			}else{
				return start;
			}
		}
		Node follow = start;
		while(prev.next != null){
			prev = prev.next;
			if(prev.next != null){
				prev = prev.next;
				follow = follow.next;
			}else{
				break;
			}
		}
		return follow;
	}
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Node n1 = new Node("n1");
		Node n2 = new Node("n2");
		Node n3 = new Node("n3");
		Node n4 = new Node("n4");
//		Node n5 = new Node("n5");
//		Node n6 = new Node("n6");
		n1.next = n2;
		n2.next = n3;
		n3.next = n4;
//		n4.next = n5;
//		n5.next = n6;
		Node res = findMiddle(n1);
		System.out.println(res.data);
	}

}
    原文作者:songxueyu
    原文地址: https://blog.csdn.net/songxueyu/article/details/47022575
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞