您的位置:首页 > 编程语言 > Java开发

用java实现单向链表

2015-01-16 10:46 393 查看
主要就是简单的指针移动,之前有人让我帮改了一个链表的程序,但我觉得实现有问题 改完 自己又写了一个,代码在下面

public class MyLinkedList {

int
size;

Node
head;

Node
tail;

public
MyLinkedList() {

size =
0;

head =
null;

tail =
null;

}

public void
addElement(A inNode) {

if (head ==
null) {

head = tail
= new Node(inNode);

} else
{

tail.next =
new Node(inNode);

tail =
tail.next;

}

size++;

}

public void
updateElement(int index, A content) {

if (index
< 0 || index >= size) {

return;

}

Node
curNode = head;

while (index
> 0) {

curNode =
curNode.next;

index--;

}

curNode.content = content;

}

public A
getElement(int index) {

if (index
< 0 || index >= size) {

return
null;

}

Node
curNode = head;

while (index
> 0) {

curNode =
curNode.next;

index--;

}

return
curNode.content;

}

public void
deleteElement(int index) {

if (index
< 0 || index >= size) {

return;

}

if (index ==
0) {

head =
head.next;

if (size ==
1) {

tail =
null;

}

size--;

return;

}

Node
preNode = null;

Node
curNode = head;

while (index
> 0) {

preNode =
curNode;

curNode =
curNode.next;

index--;

}

preNode.next
= curNode.next;

if (index ==
(size - 1)) {

tail =
preNode;

}

size--;

}

public void
deleteElement(A deleNode) {

//
这里可以用来报异常

if (size ==
0) {

return;

}

if
(head.content.equals(deleNode)) {

head =
head.next;

if (size ==
1) {

tail =
null;

}

size--;

return;

}

Node
curNode = head.next;

Node
preNode = head;

while
(curNode != null) {

if
(curNode.content.equals(deleNode)) {

if (curNode
== tail) {

preNode.next
= null;

tail =
preNode;

} else
{

preNode.next
= curNode.next;

}

size--;

return;

}

preNode =
curNode;

curNode =
curNode.next;

}

return;

}

public void
showList() {

if (size ==
0) {

System.out.println("链表为空");

return;

}

Node
curNode = head;

while
(curNode != null) {

System.out.print(curNode.content + "->");

curNode =
curNode.next;

}

System.out.println("null");

}

public
static void main(String[] args) {

MyLinkedList
myLinkedList = new MyLinkedList();

myLinkedList.addElement("A");

myLinkedList.addElement("B");

myLinkedList.addElement("C");

myLinkedList.addElement("D");

myLinkedList.showList();

myLinkedList.deleteElement("D");

myLinkedList.showList();

myLinkedList.updateElement(2, "E");

myLinkedList.showList();

System.out.println(myLinkedList.getElement(1));

myLinkedList.deleteElement(2);

myLinkedList.showList();

}

}

class Node {

public
Node(A content) {

this.content
= content;

next =
null;

}

A
content;

Node
next;

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