单链表反序

面试题: 将a-z的26个字母加入一个单链表,输出,然后反序后再输出

/**
 * 
 * @author Jason Li 2014-5
 * 
 *  面试题: 要求将a-z的26个字母加入一个单链表,输出,然后反序后再输出
 * 
 */

public class SingleLinkedListTest {

	public static void main(String[] args) {
		SingleLinkedList sll = new SingleLinkedList();
		
		for (int i = 0; i < 26; i++) {
			sll.add((char)('a' + i));
		}		
		sll.show();		
		sll.reverse();	
		sll.show();
	}

}

//简单的单链表
class SingleLinkedList {

	private Node head;// 头指针
	private Node tail;// 尾指针

	public SingleLinkedList() {
		Node tem = new Node();
		tem.content = 0;
		tem.next = null;
		this.head = this.tail = tem;
	}

	//在链表尾部添加
	public void add(Object o) {
		Node tem = new Node();
		tem.content = o;
		tem.next = null;
		tail.next = tem;
		tail = tem;
	}

	// 反序
	public void reverse() {
		Node insert_point = head.next; //插入位置
		Node cur = insert_point.next; //待插入的节点
		Node tmp;
		
		while (cur != null) {
			tmp = cur.next; //下一个待插入节点
			cur.next = insert_point;//把cur节点插入到插入点之前,
			insert_point = cur; //然后当前节点下变为插入点
			cur = tmp; 
		}
		tail = head.next;
		tail.next = null;
		head.next = insert_point;

	}

	// 显示
	public void show() {
		Node cur = head.next;
		while (cur != null) {
			System.out.print(cur.content);
			cur = cur.next;
			if (cur != null)
				System.out.print("->");
		}
		System.out.println();
	}

	// 节点类
	private class Node {
		public Object content;
		public Node next;
	}

}

 

转载于:https://my.oschina.net/jasonli0102/blog/270696

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值