要实现单链表,首先要建立链表的节点类:
- /**
- * 单链表的节点类,单链表的实现。
- */
- package com.ty.third;
- /**
- * @author liming
- *
- */
- public class SLLNode<T> {
- //你要储存的信息单位
- public T info;
- //指向下一个元素
- public SLLNode<T> next;
- public SLLNode(T i)
- {
- this(i,null);
- }
- //第二个参数传入node是为了快速建立链表
- public SLLNode(T i, SLLNode<T> node)
- {
- this.info = i;
- this.next = node;
- }
- }
/**
* 单链表的节点类,单链表的实现。
*/
package com.ty.third;
/**
* @author liming
*
*/
public class SLLNode<T> {
//你要储存的信息单位
public T info;
//指向下一个元素
public SLLNode<T> next;
public SLLNode(T i)
{
this(i,null);
}
//第二个参数传入node是为了快速建立链表
public SLLNode(T i, SLLNode<T> node)
{
this.info = i;
this.next = node;
}
}
然后,单链表类:
- package com.ty.third;
- public class SLLList<T>
- {
- protected SLLNode<T> head, tail;
- //当前的节点,用于遍历所有元素
- private SLLNode<T> cur = null;
- //创建一个空的单链表
- public SLLList()
- {
- head = tail = null;
- }
- //添加头节点
- public void addToHead(T info)
- {
- SLLNode<T> sllNode = new SLLNode<T>(info);
- //如果链表为空
- if(head == null)
- {
- head = sllNode;
- tail = head;
- }
- //链表不为空
- else
- {
- sllNode.next = head;
- head = sllNode;
- }
- }
- //打印所有链表节点
- public void printAllNode()
- {
- SLLNode<T> temp = null;
- for(prepare();hasNext();next())
- {
- temp = getNextNode();
- System.out.println(temp.info);
- }
- }
- //添加尾节点
- public void addToTail(T info)
- {
- SLLNode<T> sllNode = new SLLNode<T>(info);
- //链表为空,则直接创建头节点
- if(head == null)
- {
- addToHead(info);
- }
- //链表不为空,加到链表尾部
- else
- {
- tail.next = sllNode;
- tail = sllNode;
- }
- }
- //列表是否为空
- public boolean isEmpty()
- {
- return (head == null);
- }
- //判断列表是否有下一个元素
- public boolean hasNext()
- {
- if(isEmpty())
- return false;
- if(cur.next == null)
- return false;
- return true;
- }
- //获得当前元素
- public SLLNode<T> getNextNode()
- {
- return cur.next;
- }
- //当前元素下移
- public void next()
- {
- cur = cur.next;
- }
- //为遍历准备
- public void prepare()
- {
- cur = new SLLNode<T>(null);
- cur.next = head;
- }
- public static void main(String []args)
- {
- SLLList<String> sllList = new SLLList<String>();
- sllList.addToHead("Joking");
- sllList.addToHead("Testing");
- sllList.addToTail("Lily");
- sllList.printAllNode();
- SLLList<String> sllList2 = new SLLList<String>();
- for(sllList.prepare(); sllList.hasNext(); sllList.next())
- {
- sllList2.addToHead(sllList.getNextNode().info);
- }
- sllList2.printAllNode();
- }
- }