单链表

单链表,遍历一次,找到中间节点。(这个主要要考虑到单链表元素个数是奇/偶数的情况,这个是关键的,我当时就是差点没考虑到这个)。



package Test;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class ListFindHalf {

	private static Integer findHalf(Iterator it, Iterator itt) {
		// Iterator itt=it;
		// while (itt.hasNext()) {
		// System.out.println("ss=" + itt.next());
		// }
		// while (it.hasNext()) {
		// System.out.println("tt=" + it.next());
		// }
		// while (it.hasNext()){
		// it.next();
		// if (it.hasNext()){
		// it.next();
		// itt.next();
		// } else{
		// // System.out.println("sd="+ itt.next());
		// return (Integer) itt.next();
		// }
		// }
		// return 8888;
		do {
			if (it.hasNext()) {
				it.next();
			}
			if (it.hasNext()) {
				it.next();
				if (it.hasNext()) {
					itt.next();
				}
			} else {
				return (Integer) itt.next();
			}
		} while (it.hasNext());
		return 8888;
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		int n = 8;
		List list = new ArrayList();
		for (int i = 0; i <= n; i++) {
			list.add(i);
		}
		System.out.println("halfPoint value="
				+ findHalf(list.iterator(), list.iterator()).intValue());
	}

}

你可能感兴趣的:(java)