首页 > 代码库 > Java 实现单链表反序

Java 实现单链表反序

//单链表反序
public class SingleLinkedListReverse {
	
	public static void main(String[] args) {
		Node head = new Node(0);
		Node temp = null;
		Node cur = null;
		
		for (int i = 1; i <= 10; i++) {
			temp = new Node(i);
			if (i == 1) {
				head.setNext(temp);
			} else {
				cur.setNext(temp);
			}
			cur = temp;
		}//10.next = null;
		
		Node h = head;
		while (h != null) {
			System.out.print(h.getData() + "\t");
			h = h.getNext();
		}
		System.out.println();
		
		//反转1
//		h = Node.reverse1(head);
//		while (h != null) {
//			System.out.print(h.getData() + "\t");
//			h = h.getNext();
//		}
		
		//反转2
		h = Node.reverse1(head);
		while (h != null) {
			System.out.print(h.getData() + "\t");
			h = h.getNext();
		}
		
		
	}
}

/*
 * 单链表的每个节点都含有指向下一个节点属性
 */
class Node {
	Object data;//数据对象 
	Node next; //下一节点
	
	Node(Object d) {
		this.data = http://www.mamicode.com/d;>