面试题: 将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;
}
}