`
mtnt2008
  • 浏览: 362838 次
  • 性别: Icon_minigender_1
  • 来自: 北京
文章分类
社区版块
存档分类
最新评论

单向链表---Java版

阅读更多

 

1. 节点类

 

package com.linkedlist;

public class SLLNode {

	public Object info;

	public SLLNode next;

	public SLLNode(Object e1) {
		info = e1;
		next = null;
	}

	public SLLNode(Object e1, SLLNode ptr) {
		info = e1;
		next = ptr;
	}

}
 

2. 链表类

 

package com.linkedlist;

public class SLList {

	protected SLLNode head = null;

	public SLList() {
		;
	}

	public boolean isEmpty() {
		return head == null;
	}

	public Object first() {
		return head.info;
	}

	public void printAll() {
		for (SLLNode tmp = head; tmp != null; tmp = tmp.next) {
			System.out.println(tmp.info);
		}
	}

	// 好好理解一下
	public void add(Object e1) {
		head = new SLLNode(e1, head);
		// info = e1;
		// next = ptr;
	}

	public Object find(Object e1) {
		SLLNode tmp = head;
		for (; tmp != null && !e1.equals(tmp.info); tmp = tmp.next) {
			;
		}
		if (tmp == null) {
			return null;
		} else {
			return tmp.info;
		}
	}

	public Object deleteHead() {
		Object e1 = head.info;
		head = head.next;
		return e1;
	}

	public void delect(Object e1) {
		if (head != null) {
			if (e1.equals(head.info)) {
				head = head.next;
			} else {
				SLLNode pred = head, tmp = head.next;
				for (; tmp != null && !(tmp.info.equals(e1)); pred = pred.next, tmp = tmp.next) {
					;
				}
				if (tmp != null) {
					pred.next = tmp.next;
				}
			} // end else
		}// end if
	}

}
 

3. 简单测试

 

package com.linkedlist;

public class Test {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
		SLList list = new SLList();
		list.add("test1");
		list.add("test2");
		list.add(1);
		list.add(2);
		System.out.println(list.deleteHead());
		System.out.println(list.find(1));
		System.out.println(list.isEmpty());
		//list.delect("test2");
		System.out.println("------------------------");
		list.printAll();

	}

}

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics