您的位置:首页 > 理论基础 > 数据结构算法

数据结构代码-简单链表

2012-11-22 17:40 309 查看
/**
* 简单链表节点
*/
package linklist;

/**
*
*/
public class Link {
int iData;
double dData;
public Link next;

public Link(int iData, double dData) {
this.iData = iData;
this.dData = dData;
next = null;
}

public void displayLink() {
System.out.println("{" + iData + "," + dData + "}");
}
}
/**
* 简单链表数据结构
*/
package linklist;

/**
*
*/
public class LinkList
{
private Link first;

public LinkList()
{
first = null;
}

/**
* 判断链表是否为空
*
* @return
*/
public boolean isEmpty()
{
return first == null;
}

/**
* 在链表头部插入元素
*
* @param iData
* @param dData
*/
public void insertFirst(int iData, double dData)
{
Link link = new Link(iData, dData);
link.next = first;
first = link;
}

/**
* 在链表头部删除元素
*
* @return
* @throws EmptyLinkListException
*/
public Link deleteFirst()
throws EmptyLinkListException
{
if (isEmpty())
{
throw new EmptyLinkListException();
}
else
{
Link temp = first;
first = first.next;
return temp;
}
}

/**
* 查找指定关键字的节点
*
* @param key
* @return
*/
public Link find(int key)
{
Link current = first;
while (current != null)
{
if (key == current.iData)
{
break;
}
else
{
current = current.next;
}
}
return current;
}

/**
* 删除指定关键字的节点
*
* @param key
* @return
* @throws EmptyLinkListException
*/
public Link delete(int key)
throws EmptyLinkListException
{
if (isEmpty())
{
throw new EmptyLinkListException();
}
else if (first.iData == key)
{// 要找的元素在首节点
return deleteFirst();
}
else
{
Link current = first.next;
Link previous = first;
while (current != null)
{
if (current.iData == key)
{
previous.next = current.next;
break;
}
previous = current;
current = current.next;
}
return current;
}
}

/**
* 按照整型key升序插入元素,规则为大于前一个元素,小于或者等于后一个元素
* @see [类、类#方法、类#成员]
*/
public void insertByAscend(int iData, double dData)
{
Link link = new Link(iData, dData);
//如果链表为空,或键值比表头还小也做表头
if (isEmpty() || iData <= first.iData)
{
link.next = first;
first = link;
}
else
{
Link current = first;
Link next = current.next;
while (iData > current.iData)
{
if (next == null || iData <= next.iData)
{
link.next = current.next;
current.next = link;
break;
}
current = next;
next = current.next;
}
}
}

/**
* 遍历链表
*/
public void displayList()
{
Link current = first;
while (current != null)
{
current.displayLink();
current = current.next;
}
}

/**
* 返回首元素
* @return
* @see [类、类#方法、类#成员]
*/
public Link getFirst()
{
return first;
}
}
/**
* 简单链表测试类
*/
package linklist;

/**
*
*/
public class LinkListTest {

/**
* @param args
*/
public static void main(String[] args) {
LinkList linkList = new LinkList();
linkList.insertFirst(1, 1.1);
linkList.insertFirst(2, 2.2);
linkList.insertFirst(3, 3.3);
try {
linkList.delete(3);
linkList.displayList();
} catch (EmptyLinkListException e) {
e.printStackTrace();
}
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: